Skip to content

Instantly share code, notes, and snippets.

@danwarfel
Last active April 10, 2017 08:45
Show Gist options
  • Save danwarfel/5f08cd559606f2acade1 to your computer and use it in GitHub Desktop.
Save danwarfel/5f08cd559606f2acade1 to your computer and use it in GitHub Desktop.
This function illustrates how to programmatically select all text inside any HTML element
function selectText(element) {
if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
element.select();
return;
}
var rangeObj, selection;
if (document.createRange) { // IE >=9 and all other browsers
rangeObj = document.createRange();
rangeObj.selectNodeContents(element);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(rangeObj);
} else if (document.body.createTextRange) { // IE <9
rangeObj = document.body.createTextRange();
rangeObj.moveToElementText(element);
rangeObj.select();
}
}
// from https://www.thewebflash.com/select-or-deselect-text-inside-an-element-using-js/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment