jQuery Select elements

This script will programatically select elements on the screen similar to how a user would select/highlight items manually.

by Dylan Schadeck

HTML

<div id="selectme">
    <p>Some text goes here!</p>
    <p>Moar text!</p>
    <img src="http://placehold.it/50x50" alt="">
</div>
<p>Click me!</p>

JavaScript

jQuery.fn.selectText = function(){
    var doc = document
        , element = this[0]
        , range, selection
    ;
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

$(function() {
    $('p').click(function() {
        $('#selectme').selectText();
    });
});