admin管理员组

文章数量:1394181

I'm getting the selected text from textarea but I can't get it from a div. I'm trying with document.getElementById('myDiv') but it doesn't work.

To be more specific. When I have text, using this method I can get the selected text

function TestSelection () 
{
            if (window.getSelection) {  
                var selectionRange = window.getSelection(); 
                alert ("The text content of the selection:\n" + selectionRange.toString());
            }
}

but I cant specify the div to get it's selected text. Only from this div, not from another. I tried var value = document.getElementById("myDiv").innerHTML; and then value.getSelection but it doesn't work too. Thank you very much!!!

I'm getting the selected text from textarea but I can't get it from a div. I'm trying with document.getElementById('myDiv') but it doesn't work.

To be more specific. When I have text, using this method I can get the selected text

function TestSelection () 
{
            if (window.getSelection) {  
                var selectionRange = window.getSelection(); 
                alert ("The text content of the selection:\n" + selectionRange.toString());
            }
}

but I cant specify the div to get it's selected text. Only from this div, not from another. I tried var value = document.getElementById("myDiv").innerHTML; and then value.getSelection but it doesn't work too. Thank you very much!!!

Share Improve this question edited Dec 5, 2012 at 16:11 jimakos17 asked Dec 5, 2012 at 14:53 jimakos17jimakos17 9354 gold badges15 silver badges34 bronze badges 1
  • This might help: stackoverflow./q/5379120/1066234 – Avatar Commented Mar 20, 2023 at 14:50
Add a ment  | 

5 Answers 5

Reset to default 4

Simply ,do the following :

var ss=getSelection();

ss.baseNode.data.substring(ss.baseOffset,ss.extentOffset);

Use the innerHTML property

var html = document.getElementById('myDiv').innerHTML;

You should use innerHTML property:

var value = document.getElementById("myDiv").innerHTML;

You should use Selection

var selObj = window.getSelection();
window.alert(selObj); 

for jquery

var str = $("#myDiv").text();

str is the text

本文标签: javascriptHow to get Selected Text from DIVStack Overflow