Select Div Content With a Single Click

Copying a text from a website can be uncomfortable. Help your site visitors select the text with a single click of a mouse button with this simple trick.

select div text click javascript

Check out the Live Demo or click any code snippet on this page.

In case of an <input> element we have an easy job because we can solve that in a just a couple lines of code:

$(".selectable").click(function() {
    $(this).select();
});

Unfortunately this doesn’t work for whole div sections and many others.

The Code

Add the selectable class in your HTML code to each section you want to make selectable, like in the example below:

<h1 class="selectable">At persius imperdiet</h1>
<div class="selectable">
    <p>Lorem ipsum dolor sit amet</p>
</div>
<div class="selectable">
    <p>Quo debet vivendo ex.</p>
</div>

The JavaScript code parses the document and adds a custom ID to each element having our selector class and an onclick event listener, which calls the selectText function. This function takes the container ID as the input and selects the calculated range. jQuery is required.

$(document).ready(function () {
    var selectcounter = 1;
    
    $(".selectable").each(function() {
        idja = "selectable" + selectcounter;
        $(this).attr('id', idja);
        $(this).attr('onclick', 'selectText("' + idja + '")');
        selectcounter++;
    });     
});

function selectText(containerid) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
    }
}

We can set the mouse pointer to change when a selectable element is hovered with the CSS code below.

.selectable {
    cursor: pointer;
}