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.


 i think the following code may help you

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

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