Select the Content of HTML Element

This article shows you how to select the content added into HTML elements: input text field, textarea, and DIV.
It is simple to select the text added into an input text field or into a textarea, just apply the select() method to the input or textarea element.
element.select()
Example. When click on an input text field or textarea, selects its content.
<form action="#" method="post">
 <input type="text" name="inp1" id="inp1" value="Click to select" /><br/>
 <textarea name="txta1" id="txta1" cols="20" rows="3">Click to select</textarea>
</form>

<script type="text/javascript">
// registers on click event to select #inp1 field data
document.getElementById('inp1').onclick = function(){ this.select(); }
  /* the word this represents the clicked element */

// registers on click event to select #txta1 textarea data
document.getElementById('txta1').onclick = function(){ this.select(); }
</script>
- Demo. Click on the input text field and textarea.

Select the content of DIV element

If you want to select all the content added intoi a DIV (or other HTML tag, like <span>, <li>, <blockquote>, etc.), use theselectElmCnt() function, presented below.
- This function receives an object with the element you want to select.

Code of the theselectElmCnt() function
// selects the content of an element. Receives the object with that element
function selectElmCnt(elm) {
  // for Internet Explorer
  if(document.body.createTextRange) {
    var range = document.body.createTextRange();
    range.moveToElementText(elm);
    range.select();
  }
  else if(window.getSelection) {
    // other browsers
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(elm);
    selection.removeAllRanges();
    selection.addRange(range);
  }
}
- Example. When click on the text added into a DIV, selects all its content.
<div id="exdv1">
 Courses for Web Programming and Development: http://CoursesWeb.net<br/>
 <span>Other line with child element.</span>
</div>

<script type="text/javascript">
// selects the content of an element. Receives the object with that element
function selectElmCnt(elm) {
  // for Internet Explorer
  if(document.body.createTextRange) {
    var range = document.body.createTextRange();
    range.moveToElementText(elm);
    range.select();
  }
  else if(window.getSelection) {
    // other browsers
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(elm);
    selection.removeAllRanges();
    selection.addRange(range);
  }
}

// registers on click event to use the selectElmCnt() function whewn click on #exdv1 div
document.getElementById('exdv1').onclick = function(){ selectElmCnt(this); }
  /* the word this represents the clicked element */
</script>
Demo (click the text):
Courses for Web Programming and Development: http://CoursesWeb.net
Other line with child element.