Skip to content

Instantly share code, notes, and snippets.

@elundmark
Last active January 24, 2020 14:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elundmark/8037991 to your computer and use it in GitHub Desktop.
Save elundmark/8037991 to your computer and use it in GitHub Desktop.
Select All Text in any element, cross-browser
function selectAllText (elem) {
var range, selection;
// A jQuery selector should pass through too
elem = (elem.jquery && elem.length) ? elem[0] : elem;
if ( !elem ) {
return;
} else if ( elem.nodeName.match(/^(INPUT|TEXTAREA)$/i) ) {
elem.focus();
elem.select();
} else if ( typeof document.body.createTextRange === "function" ) {
// IE or Opera <10.5
range = document.body.createTextRange();
range.moveToElementText(elem);
range.select();
} else if ( typeof window.getSelection === "function" ) {
selection = window.getSelection();
if ( typeof selection.setBaseAndExtent === "function" ) {
// Safari
selection.setBaseAndExtent(elem, 0, elem, 1);
} else if ( typeof selection.addRange === "function"
&& typeof selection.removeAllRanges === "function"
&& typeof document.createRange === "function" ) {
// Mozilla or Opera 10.5+
range = document.createRange();
range.selectNodeContents(elem);
selection.removeAllRanges();
selection.addRange(range);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment