Selecting text inside <div>

is it possible to use a javascript function to select text within a <div>?

I know it’s possible to use document.getElementById(id).select() to select text within an input or textarea, but what about divs or spans?

You would need to use the DOM to get the value of the text inside of the DIV or SPAN.

Something like this (off of the top of my head so this may be wrong):

$text = document.getElementById(‘myid’).firstChild.nodeValue;

Wouldn’t that simply retrieve the text?
I want it to be selected so the user can CTRL+C it or drag it somewhere

In that case I am not sure JavaScript can do that

I see, so it’s only possible with input or textareas?

As far as I know. I would have though a guru would have jumped in and corrected my if I was wrong already so I am pretty sure it is not possible.

hi

 i think the following code may help you

<script type="text/javascript">
	function fnSelect(objId) {
		fnDeSelect();
		if (document.selection) {
		var range = document.body.createTextRange();
 	        range.moveToElementText(document.getElementById(objId));
		range.select();
		}
		else if (window.getSelection) {
		var range = document.createRange();
		range.selectNode(document.getElementById(objId));
		window.getSelection().addRange(range);
		}
	}
		
	function fnDeSelect() {
		if (document.selection) document.selection.empty();
		else if (window.getSelection)
                window.getSelection().removeAllRanges();
	}
	</script>
<body>

<div id="test1">
	<p>jhsdgfhlsdlfkjsdklgjs</p>
	<p>jhsdgfhlsdlfkjsdklgjs</p>
	<p>jhsdgfhlsdlfkjsdklgjs</p>
</div>
<div id="test2">
	<p>jhsdgfhlsdlfkjsdklgjs</p>
	<p>jhsdgfhlsdlfkjsdklgjs</p>
	<p>jhsdgfhlsdlfkjsdklgjs</p>
</div>
<a href="javascript:fnSelect('test1');">Select 1</a>
<a href="javascript:fnSelect('test2');">Select 2</a>
<a href="javascript:fnDeSelect();">DeSelect</a>
</body>