3

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!!!

jimakos17
  • 905
  • 4
  • 14
  • 33

5 Answers5

4

Simply ,do the following :

var ss=getSelection();

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

enter image description here

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
2

Use the innerHTML property

var html = document.getElementById('myDiv').innerHTML;
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Thank you for your answer. I updated my question to be more specific because I still can't do it. Thank you again. – jimakos17 Dec 05 '12 at 16:15
1

You should use innerHTML property:

var value = document.getElementById("myDiv").innerHTML;
VisioN
  • 143,310
  • 32
  • 282
  • 281
1

You should use Selection

var selObj = window.getSelection();
window.alert(selObj); 
Ivan Solntsev
  • 2,081
  • 2
  • 31
  • 40
-1

for jquery

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

str is the text

Waqleh
  • 9,741
  • 8
  • 65
  • 103