-
-
Save tennisonchan/47abb2c99a0e79abca257f052d46bbed to your computer and use it in GitHub Desktop.
get selection string #js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getSelectionString(el, win) { | |
win = win || window; | |
var doc = win.document, sel, range, prevRange, selString; | |
if (win.getSelection && doc.createRange) { | |
sel = win.getSelection(); | |
if (sel.rangeCount) { | |
prevRange = sel.getRangeAt(0); | |
} | |
range = doc.createRange(); | |
range.selectNodeContents(el); | |
sel.removeAllRanges(); | |
sel.addRange(range); | |
selString = sel.toString(); | |
sel.removeAllRanges(); | |
prevRange && sel.addRange(prevRange); | |
} | |
else if (doc.body.createTextRange) { | |
range = doc.body.createTextRange(); | |
range.moveToElementText(el); | |
range.select(); | |
} | |
return selString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment