最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get Selected Text from DIV - Stack Overflow

programmeradmin0浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论