Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all DIV text with single mouse click

Tags:

javascript

css

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!

like image 611
Acyra Avatar asked Jul 23 '09 17:07

Acyra


People also ask

How do I select all text in a div?

To select all text inside an element such as DIV, we can simply use JavaScript document. createRange() method to create a range, and than using range. selectNodeContents() we can set node range (start and end), after which use selection. addRange() to select the range of the element.

Can you click on a div?

The answer is definitely yes, but you will need to write javascript code for it. We can use a click handler on the div element to make it clickable.


1 Answers

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.

like image 141
Denis Sadowski Avatar answered Sep 20 '22 07:09

Denis Sadowski