Last active
January 24, 2020 14:29
-
-
Save elundmark/8037991 to your computer and use it in GitHub Desktop.
Select All Text in any element, cross-browser
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 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