Updated on 7/13/2008.
Here is a function that when called on a particular HTML element will auto-select all of its inner text. The function works on elements such as INPUT (text), TEXTAREA, DIV, SPAN, TD, and PRE. It is also cross browser compatible.
Below this code is a working demo.
autoSelect(el):
var autoSelect = function (el) {
if(el.tagName === "TEXTAREA" || (el.tagName === "INPUT" && el.type === "text")) {
el.select();
return;
}
if (window.getSelection) { // FF, Safari, Opera
var sel = window.getSelection();
var range = document.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection) { // IE
document.selection.empty();
var range = document.body.createTextRange();
range.moveToElementText(el);
range.select();
}
};
Example function call: autoSelect(document.getElementById("myDiv"));
This script was successfully tested in Windows versions of Internet Explorer 5.5 - 7, Firefox 1.5 - 3, Opera 9 and Safari 3.
PRE: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam ultrices vestibulum elit. Mauris congue sapien sed dolor. Pellentesque sem augue, porttitor id, placerat ac, congue ac, eros. Etiam fermentum consectetuer pede. Donec tincidunt. Suspendisse non nisi. In hac habitasse platea dictumst. In hac habitasse platea dictumst. Integer porta egestas sapien.
| TD: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam ultrices vestibulum elit. Mauris congue sapien sed dolor. Pellentesque sem augue, porttitor id, placerat ac, congue ac, eros. Etiam fermentum consectetuer pede. Donec tincidunt. Suspendisse non nisi. In hac habitasse platea dictumst. In hac habitasse platea dictumst. Integer porta egestas sapien. |
Comments