Example
function SelectAll (ID) {
var h = document, I = H.getelementbyid (id), D, G;
if (H.body.createtextrange) {
D = Document.body.createTextRange ();
D.movetoelementtext (i);
D.select ()
} else {
if (window.getselection) {
g = window.getselection ();
D = Document.createrange ();
D.selectnodecontents (i);
G.removeallranges ();
G.addrange (d)
}
}
}
Example
<title> Get selected text </title>
<body>
<p>
Here is to get user-selected range in IE with var selectedtext = Document.selection.createRange ();
At this time, the object is to get the user selected text SelectedText = Selectedtext.text; In FF, Safari, Opera,
It's easy to get user-selected range in chrome and other standard browsers: var selectedtext = window.getselection ();
</p>
<button id= "button" > Selected text, click Button </button>
<script type= "Text/javascript" >
var obtn = document.getElementById ("button");
Obtn.onclick = function () {
var SelectedText;
if (window.getselection) {
Selectedtext=window.getselection ();
}else if (document.selection) {
Selectedtext=document.selection.createrange (). text;
}
alert (SelectedText);
};
</script>
</body>
JS Select partial text
<script>
Function foo () {
var textbox= document.getelementbyid (' target ');
SelectText (textbox,0,14); //Select first 14 characters
}
/**
* @textbox: Text to manipulate
* @startIndex: To select the index of the first character in the text
* @stopIndex: To select the index after the last character of the text
*/
function SelectText (textbox,startindex,stopindex) {
if (textbox.setselectionrange) {
Textbox.setselectionrange (Startindex,stopindex);
}else if (textbox.createtextrange) {
var range=textbox.createtextrange ();
Range.collapse (TRUE);
Range.movestart (' character ', startIndex);
Range.moveend (' character ', stopindex-startindex);
Range.Select ();
}
Textbox.focus ();
}
</script>
<textarea cols= rows= "a" id= "target"
<div>php</div>
<div >qqq</div>
</textarea>
<input type= "button" onclick= "foo ()" value= "click"