JavaScript Ninja - Implement .select() For All HTML-Elements

Posted at




You probably know that <textarea> have .select() method, that could help you easily select all of the textual-content on the element,

I've developed *some script* to help users of XDA better view the [code] sections, initially I've used <textarea> elements, since the content of [code] should be used for comments and source-codes,

but oddly-enough I've noticed some users embed HTML segments in the [code] (which translated to <pre>) naturally I've switched to using <pre> to resolved it, but <pre> does not have any native .select() method to select the internal-content.

it is easily implementable.

HTMLPreElement.prototype.select = function(){
/* 1. why implement ".select()"? --- textarea has one, pre doesn't. But I still want to copy */
/* 2. before calling ".select()" --- call "window.getSelection().removeAllRanges();" -- avoid "discontinue-ranges" */
var
me = this
, range = document.createRange()
;
range.selectNodeContents(me);
document.getSelection().addRange(range);

return true;
};