I liked lepe's answer except for a few things:
- Browser-sniffing, jQuery or no isn't optimal
- DRY
- Doesn't work in IE8 if obj's parent doesn't support createTextRange
- Chrome's ability to use setBaseAndExtent should be leveraged (IMO)
- Will not select text spanning across multiple DOM elements (elements within the "selected" element). In other words if you call selText on a div containing multiple span elements, it will not select the text of each of those elements. That was a deal-breaker for me, YMMV.
Here's what I came up with, with a nod to lepe's answer for inspiration. I'm sure I'll be ridiculed as this is perhaps a bit heavy-handed (and actually could be moreso but I digress). But it works and avoids browser-sniffing and that's the point.
selectText:function(){ var range, selection, obj = this[0], type = { func:'function', obj:'object' }, // Convenience is = function(type, o){ return typeof o === type; }; if(is(type.obj, obj.ownerDocument) && is(type.obj, obj.ownerDocument.defaultView) && is(type.func, obj.ownerDocument.defaultView.getSelection)){ selection = obj.ownerDocument.defaultView.getSelection(); if(is(type.func, selection.setBaseAndExtent)){ // Chrome, Safari - nice and easy selection.setBaseAndExtent(obj, 0, obj, $(obj).contents().size()); } else if(is(type.func, obj.ownerDocument.createRange)){ range = obj.ownerDocument.createRange(); if(is(type.func, range.selectNodeContents) && is(type.func, selection.removeAllRanges) && is(type.func, selection.addRange)){ // Mozilla range.selectNodeContents(obj); selection.removeAllRanges(); selection.addRange(range); } } } else if(is(type.obj, document.body) && is(type.obj, document.body.createTextRange)) { range = document.body.createTextRange(); if(is(type.obj, range.moveToElementText) && is(type.obj, range.select)){ // IE most likely range.moveToElementText(obj); range.select(); } } // Chainable return this; }
That's it. Some of what you see is the for readability and/or convenience. Tested on Mac in latest versions of Opera, Safari, Chrome, Firefox and IE. Also tested in IE8. Also I typically only declare variables if/when needed inside code blocks but jslint suggested they all be declared up top. Ok jslint.
Edit I forgot to include how to tie this in to the op's code:
function SelectText(element) { $("#" + element).selectText(); }
Cheers