1

I am using the following code to get the position of a selected text :

var text = window.getSelection(); 
start = text.anchorOffset; 
end = text.focusOffset - text.anchorOffset;

And I want to get that selected text later .. for that I am using :

document.elementFromPoint(start,end);

However, it always returns "null".

Help please :)

Mayusu
  • 91
  • 1
  • 2
  • 11

1 Answers1

1

elementFromPoint(start,end); requires xy page coordinates, you are passing index within a string.

To get the xy page coordinates you can use Calculating xy-position of text selection . Note that the coordinates are for the viewport, so you may have to account for scrolling if you want the distance from the top of the HTML document.

getSelection().getRangeAt(0).getClientRects()[0];
// ClientRect {}
// bottom: 226
// height: 15
// left: 300.75
// right: 305.078125    
// top: 211

width: 4.328125

To get the HTML element that wraps your text node, you can use Get parent element of a selected text

window.getSelection().anchorNode.parentElement
Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • I don't understand .. how is getting the parent element of my selected text will help me to get its position ? – Mayusu Jan 27 '16 at 14:49
  • Your code was trying to find an element from a selection; I told you how to do that. Your question says nothing about getting the position of the selected text – Ruan Mendes Jan 27 '16 at 16:10
  • It does. I said "to get the position of a selected text". And I'm passing the two positions (start and end) to this function : document.elementFromPoint(start,end). My question was "Why does it return null ?" I want to get that text BY its position. – Mayusu Jan 27 '16 at 16:24
  • @Mayusu There is no element that corresponds to a text node, that's why your call returns null. I'm saying that the best you can do is to get the element that contains your selection – Ruan Mendes Jan 27 '16 at 16:31
  • @Mayusu You should make your question title clearer by indicating what you are trying to do. I had answered the question that was asked in the title. I just added some comments that explain how to do what you really wanted – Ruan Mendes Jan 27 '16 at 16:41