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 just a couple lines of code:

$(".selectable").click(function() {

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 class="selectable">
    <p>Quo debet vivendo ex.</p>

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 + '")');

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

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

.selectable {
    cursor: pointer;