Getting Selected Text

A

Alex

Pass into the function the DV's Id.

function selectext(element_id) {
var d=document;
if(d.getElementById ) {
var elem = d.getElementById(element_id);
if(elem) {
if(d.createRange) {
var rng = d.createRange();
if(rng.selectNodeContents) {
rng.selectNodeContents(elem);
if(window.getSelection) {
var sel=window.getSelection();
if(sel.removeAllRanges) sel.removeAllRanges();
if(sel.addRange) sel.addRange(rng);
}
}
} else if(d.body && d.body.createTextRange) {
var rng = d.body.createTextRange();
rng.moveToElementText(elem);
rng.select();
}
}
}
}
 
A

afrinspray

I didn't want to set the text of an element, but your function gave me
the window.getSelection() function to lead me in the right direction.
This function doesn't work for me in IE, so I made this function
below... it seems to work alright.

function getSelectedText() {

if(window.getSelection) {
return window.getSelection();
}
else if(document.selection.createRange().text) {
return document.selection.createRange().text;
}

return '';

}
 
R

RobG

afrinspray said on 28/03/2006 9:18 AM AEST:
I didn't want to set the text of an element, but your function gave me
the window.getSelection() function to lead me in the right direction.
This function doesn't work for me in IE, so I made this function
below... it seems to work alright.

function getSelectedText() {

if(window.getSelection) {
return window.getSelection();
}
else if(document.selection.createRange().text) {
return document.selection.createRange().text;
}

return '';

}


That won't work in browsers that support only DOM 0 window.getSelection,
such as Safari 1.3. If you want a better cross-browser script, try this
one at quirksmode:


<URL:http://www.quirksmode.org/js/selected.html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top