Javascript to Select or Highlight Text Inside Div


This Posts shows how to select the whole text inside 'div' element of a page on button click, so user can just right click the text and copy all of it.

JS function.


function selectText(divID) //divID contains actual id of 'div' element
{
var textC=document.getElementById(divID);
if (document.selection)
{
//Portion for IE
var div = document.body.createTextRange();
div.moveToElementText(textC);
div.select();
}
else
{
//Portion for FF
var div = document.createRange();
div.setStartBefore(textC);
div.setEndAfter(textC);
window.getSelection().addRange(div);
alert(div.value);
}
}


Now add this above function to js file being included in the page where you have to implement the text highlight inside the div. Or make a .js file put this function inside upload to some location and include to html file. Also you can choose to add above function to head section of HTML via javascript tag.

Now following is the way to call it.



Some text here...





Now your function to select/highlight whole text in a div is implemented.

Enjoy!!

Comments are appreciated.

Posted in |