[javascript] Selecting text in an element (akin to highlighting with your mouse)

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:


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


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

Am I missing something blatantly obvious?

This question is related to javascript jquery

The answer is

Plain Javascript

function selectText(node) {_x000D_
    node = document.getElementById(node);_x000D_
    if (document.body.createTextRange) {_x000D_
        const range = document.body.createTextRange();_x000D_
    } else if (window.getSelection) {_x000D_
        const selection = window.getSelection();_x000D_
        const range = document.createRange();_x000D_
    } else {_x000D_
        console.warn("Could not select text in node: Unsupported browser.");_x000D_
const clickable = document.querySelector('.click-me');_x000D_
clickable.addEventListener('click', () => selectText('target'));
<div id="target"><p>Some text goes here!</p><p>Moar text!</p></div>_x000D_
<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();
    } else if ($.browser.mozilla || $.browser.opera) {
        var selection = window.getSelection();
        var range = document.createRange();
    } else if ($.browser.safari) {
        var selection = window.getSelection();
        selection.setBaseAndExtent(text, 0, text, 1);

Similar questions with javascript tag:

Similar questions with jquery tag: