How to select text between div tag using js?

<script type="text/javascript">

function selectext()
{
document.getElementById('TheDiv').innerHTML.select()
}

</script>

<input class="button" type="button" value="Select Codes" onClick="selectext()">
<div id="TheDiv'">


<html>
<head>
<title></title>
</head>
<body>
Select Me
</body>
</html>




</div>


The codes in above doesnt work. Actually it was working when i put textarea tag instead of div tag. But i want to use div tag.

Why would you prefer to use a div over a textarea field? You can style the textarea to look like a standard div and then still have the functionality of the textarea.

Anyhow I think this free JavaScript should answer your question:
http://www.hscripts.com/scripts/JavaScript/select-div-tag.php

it can make using only div tags without textarea. But i dont know javascript. i had know only “documentgetelementbyid()”.


alert(document.getElementById('TheDiv').innerHTML)

The browser must first parse the div before you can call that function.

Hi,

If you need to use the text in your javascript code, take the solution from crmalibu.

If you want to select (highlight) the text inside the div, you could start with this function:

function selectText(divid)
{
if (document.selection)
{
var div = document.body.createTextRange();

	div.moveToElementText(document.getElementById(divid));
	div.select();
}
else
{		
	var div = document.createRange();

	div.setStartBefore(document.getElementById(divid));
	div.setEndAfter(document.getElementById(divid)) ;
	
	window.getSelection().addRange(div);
}

}

<html>
<head>
<script language="javascript">

function selectText(divid)
{
if (document.selection)
{
var div = document.body.createTextRange();

div.moveToElementText(document.getElementById("divid"));
div.select();
}
else
{
var div = document.createRange();

div.setStartBefore(document.getElementById("divid"));
div.setEndAfter(document.getElementById("divid")) ;

window.getSelection().addRange(div);
}

}

</script>
</head>

<body>

<button onclick="selectText(divid)">Select Text</button>


<div id="divid">Select Me</div>

</body>
</html>

it works. What a treat! Thanks for help!

You’re welcome