Select all DIV text with single mouse click

JavascriptCss

Javascript Problem Overview


How to highlight/select the contents of a DIV tag when the user clicks on the DIV...the idea is that all of the text is highlighted/selected so the user doesn't need to manually highlight the text with the mouse and potentially miss a bit of the text?

For example, say we've got a DIV as below:

<div id="selectable">http://example.com/page.htm</div>

...and when the user clicks on any of that URL the whole URL text is highlighted so they can easily drag the selected text around in the browser, or copy the complete URL with a right click.

Thanks!

Javascript Solutions


Solution 1 - Javascript

function selectText(containerid) {
    if (document.selection) { // IE
        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().removeAllRanges();
        window.getSelection().addRange(range);
    }
}

<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>

Now you have to pass the ID as an argument, which in this case is "selectable", but it's more global, allowing you to use it anywhere multiple times without using, as chiborg mentioned, jQuery.

Solution 2 - Javascript

UPDATE 2017:

To select the node's contents call:

window.getSelection().selectAllChildren(
    document.getElementById(id)
);

This works on all modern browsers including IE9+ (in standards mode).

Runnable Example:

function select(id) {
  window.getSelection()
    .selectAllChildren(
      document.getElementById("target-div") 
    );
}

#outer-div  { padding: 1rem; background-color: #fff0f0; }
#target-div { padding: 1rem; background-color: #f0fff0; }
button      { margin: 1rem; }

<div id="outer-div">
  <div id="target-div">
    Some content for the 
    <br>Target DIV
  </div>
</div>

<button onclick="select(id);">Click to SELECT Contents of #target-div</button>


The original answer below is obsolete since window.getSelection().addRange(range); has been deprecated

Original Answer:

All of the examples above use:

    var range = document.createRange();
    range.selectNode( ... );

but the problem with that is that it selects the Node itself including the DIV tag etc.

To select the Node's text as per the OP question you need to call instead:

    range.selectNodeContents( ... )

So the full snippet would be:

    function selectText( containerid ) {

        var node = document.getElementById( containerid );

        if ( document.selection ) {
            var range = document.body.createTextRange();
            range.moveToElementText( node  );
            range.select();
        } else if ( window.getSelection ) {
            var range = document.createRange();
            range.selectNodeContents( node );
            window.getSelection().removeAllRanges();
            window.getSelection().addRange( range );
        }
    }


Solution 3 - Javascript

There is pure CSS4 solution:

.selectable{
    -webkit-touch-callout: all; /* iOS Safari */
    -webkit-user-select: all; /* Safari */
    -khtml-user-select: all; /* Konqueror HTML */
    -moz-user-select: all; /* Firefox */
    -ms-user-select: all; /* Internet Explorer/Edge */
    user-select: all; /* Chrome and Opera */

}

user-select is a CSS Module Level 4 specification, that is currently a draft and non-standard CSS property, but browsers support it well — see #search=user-select.

.selectable{
    -webkit-touch-callout: all; /* iOS Safari */
    -webkit-user-select: all; /* Safari */
    -khtml-user-select: all; /* Konqueror HTML */
    -moz-user-select: all; /* Firefox */
    -ms-user-select: all; /* Internet Explorer/Edge */
    user-select: all; /* Chrome and Opera */

}

<div class="selectable">
click and all this will be selected
</div>

Read more on user-select here on MDN and play with it here in w3scools

Solution 4 - Javascript

The answer of Neuroxik was really helpful. I had only a trouble with Chrome, because when I clicked on an external div, It did not work. I could solve it removing the old ranges before add the new range:

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().removeAllRanges();
		window.getSelection().addRange(range);
	}
}
<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>

Solution 5 - Javascript

For content editable stuff (not regular inputs, you need to use selectNodeContents (rather than just selectNode).

NOTE: All the references to "document.selection" and "createTextRange()" are for IE 8 and lower... You'll not likely need to support that monster if you're attempting to do tricky stuff like this.

function selectElemText(elem) {

	//Create a range (a range is a like the selection but invisible)
	var range = document.createRange();

	// Select the entire contents of the element
	range.selectNodeContents(elem);

	// Don't select, just positioning caret:
	// In front 
	// range.collapse();
	// Behind:
	// range.collapse(false);

	// Get the selection object
	var selection = window.getSelection();

	// Remove any current selections
	selection.removeAllRanges();

	// Make the range you have just created the visible selection
	selection.addRange(range);

}

Solution 6 - Javascript

Using a text area field, you could use this: (Via Google)

<form name="select_all">

    <textarea name="text_area" rows="10" cols="80" 
    onClick="javascript:this.form.text_area.focus();this.form.text_area.select();">

    Text Goes Here 

    </textarea>
</form>

This is how I see most websites do it. They just style it with CSS so it doesn't look like a textarea.

Solution 7 - Javascript

This snippet provides the functionality you require. What you need to do is add an event to that div that which activates fnSelect in it. A quick hack that you totally shouldn't do and possibly might not work, would look like this:

document.getElementById("selectable").onclick(function(){
    fnSelect("selectable");
});

Obviously assuming that the linked to snippet had been included.

Solution 8 - Javascript

I found it useful to wrap this function as a jQuery plugin:

$.fn.selectText = function () {
	return $(this).each(function (index, el) {
		if (document.selection) {
			var range = document.body.createTextRange();
			range.moveToElementText(el);
			range.select();
		} else if (window.getSelection) {
			var range = document.createRange();
			range.selectNode(el);
			window.getSelection().addRange(range);
		}
	});
}

So, it becomes a reusable solution. Then you can do this:

<div onclick="$(this).selectText()">http://example.com/page.htm</div>

And it will selected test in the div.

Solution 9 - Javascript

How about this simple solution? :)

<input style="background-color:white; border:1px white solid;" onclick="this.select();" id="selectable" value="http://example.com/page.htm">

Sure it is not div-construction, like you mentioned, but still it is worked for me.

Solution 10 - Javascript

Niko Lay: How about this simple solution? :)

`<input style="background-color:white; border:1px white solid;" onclick="this.select();" id="selectable" value="http://example.com/page.htm">`

.....

Code before:

<textarea rows="20" class="codearea" style="padding:5px;" readonly="readonly">

Code after:

<textarea rows="20" class="codearea" style="padding:5px;" readonly="readonly" onclick="this.select();" id="selectable">

Just this part onclick="this.select();" id="selectable" in my code worked fine. Selects all in my code box with one mouse click.

Thanks for help Niko Lay!

Solution 11 - Javascript

Easily achieved with the css property user-select set to all. Like this:

div.anyClass {
  user-select: all;
}

Solution 12 - Javascript

$.fn.selectText = function () {
    return $(this).each(function (index, el) {
        if (document.selection) {
            var range = document.body.createTextRange();
            range.moveToElementText(el);
            range.select();
        } else if (window.getSelection) {
            var range = document.createRange();
            range.selectNode(el);
            window.getSelection().addRange(range);
        }
    });
}

Above answer is not working in Chrome because addRange remove previous added range. I didnt find any solution for this beside fake selection with css.

Solution 13 - Javascript

export const selectText = (containerId) => {
  let selection = window.getSelection()
  let myElement = document.getElementById(containerId)

  if (selection.rangeCount > 0) {
    selection.removeAllRanges()
  }

  let range = document.createRange()
  range.selectNode(myElement)
  selection.addRange(range)
}**The most simplest answer works in all browsers**

Solution 14 - Javascript

try this, altn adding to oncontextmenu will gice quick access to extentions allowing input this way.

<div onclick='window.getSelection().selectAllChildren(this)' id="selectable">http://example.com/page.htm</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAcyraView Question on Stackoverflow
Solution 1 - JavascriptDenis SadowskiView Answer on Stackoverflow
Solution 2 - JavascriptisapirView Answer on Stackoverflow
Solution 3 - JavascriptMinoView Answer on Stackoverflow
Solution 4 - JavascriptJosillo DebianView Answer on Stackoverflow
Solution 5 - JavascriptbobView Answer on Stackoverflow
Solution 6 - JavascriptTyler CarterView Answer on Stackoverflow
Solution 7 - JavascriptSimon ScarfeView Answer on Stackoverflow
Solution 8 - JavascriptvitmalinaView Answer on Stackoverflow
Solution 9 - JavascriptNiko LayView Answer on Stackoverflow
Solution 10 - JavascriptIgor B.View Answer on Stackoverflow
Solution 11 - JavascripttirmeyView Answer on Stackoverflow
Solution 12 - JavascriptChristopher GibałaView Answer on Stackoverflow
Solution 13 - Javascriptchetan_vermaView Answer on Stackoverflow
Solution 14 - JavascriptTue BarfodView Answer on Stackoverflow