Javascript – Selecting text in an element (akin to highlighting with your mouse)

javascriptjquery

I would like to have users click a link, then it selects the HTML text in another element (not an input).

By "select" I mean the same way you would select text by dragging your mouse over it. This has been a bear to research because everyone talks about "select" or "highlight" in other terms.

Is this possible? My code so far:

HTML:

<a href="javascript:" onclick="SelectText('xhtml-code')">Select Code</a>
<code id="xhtml-code">Some Code here </code>

JS:

function SelectText(element) {
    $("#" + element).select();
}

Am I missing something blatantly obvious?

Best Answer

Plain Javascript

function selectText(node) {
    node = document.getElementById(node);

    if (document.body.createTextRange) {
        const range = document.body.createTextRange();
        range.moveToElementText(node);
        range.select();
    } else if (window.getSelection) {
        const selection = window.getSelection();
        const range = document.createRange();
        range.selectNodeContents(node);
        selection.removeAllRanges();
        selection.addRange(range);
    } else {
        console.warn("Could not select text in node: Unsupported browser.");
    }
}

const clickable = document.querySelector('.click-me');
clickable.addEventListener('click', () => selectText('target'));
<div id="target"><p>Some text goes here!</p><p>Moar text!</p></div>
<p class="click-me">Click me!</p>

Here is a working demo. For those of you looking for a jQuery plugin, I made one of those too.


jQuery (original answer)

I have found a solution for this in this thread. I was able to modify the info given and mix it with a bit of jQuery to create a totally awesome function to select the text in any element, regardless of browser:

function SelectText(element) {
    var text = document.getElementById(element);
    if ($.browser.msie) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if ($.browser.safari) {
        var selection = window.getSelection();
        selection.setBaseAndExtent(text, 0, text, 1);
    }
}