Skip to content

Instantly share code, notes, and snippets.

@tennisonchan
Forked from kangax/gist:05c89595c0d02b3d49bf
Last active September 19, 2016 11:46
Show Gist options
  • Save tennisonchan/47abb2c99a0e79abca257f052d46bbed to your computer and use it in GitHub Desktop.
Save tennisonchan/47abb2c99a0e79abca257f052d46bbed to your computer and use it in GitHub Desktop.
get selection string #js
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