UPDATE 2017:
To select the node's contents call:
window.getSelection().selectAllChildren(
document.getElementById(id)
);
This works on all modern browsers including IE9+ (in standards mode).
Runnable Example:
function select(id) {
window.getSelection()
.selectAllChildren(
document.getElementById("target-div")
);
}
#outer-div { padding: 1rem; background-color: #fff0f0; }
#target-div { padding: 1rem; background-color: #f0fff0; }
button { margin: 1rem; }
<div id="outer-div">
<div id="target-div">
Some content for the
<br>Target DIV
</div>
</div>
<button onclick="select(id);">Click to SELECT Contents of #target-div</button>
The original answer below is obsolete since window.getSelection().addRange(range);
has been deprecated
Original Answer:
All of the examples above use:
var range = document.createRange();
range.selectNode( ... );
but the problem with that is that it selects the Node itself including the DIV tag etc.
To select the Node's text as per the OP question you need to call instead:
range.selectNodeContents( ... )
So the full snippet would be:
function selectText( containerid ) {
var node = document.getElementById( containerid );
if ( document.selection ) {
var range = document.body.createTextRange();
range.moveToElementText( node );
range.select();
} else if ( window.getSelection ) {
var range = document.createRange();
range.selectNodeContents( node );
window.getSelection().removeAllRanges();
window.getSelection().addRange( range );
}
}
document.getElementById('selectable')
withthis
. Then you can add the functionality unobtrusively to several elements, for example several divs in a container:jQuery('#selectcontainer div').click(selectText);
– Crew