views:

182

answers:

2

I want to retrieve the xpath of the currently selected text in a browser. Using JavaScript I am able to get the selected text, but was not able to get the xpath.

I can find the xpath manually using Firebug, but I want to do it programatically. Is it possible to do it?

[EDIT] Okay, found a pointer to the solution in this thread. Modified the code from that thread to fit my needs.

A: 

Off the top of my head - but by looping through each ancestor using XSL, you can probably build up the XPath.

for each ancestor::* { newXPath = concat (local-name(.), [current_node_postion], previousGeneratedXPath)}

Recurse through each ancestor and build the complete XPath.

Thiyagaraj
+1  A: 

What if the selection spans several DOM elements, what would the path be?

I don't think you can get the selected DOM element from the getSelection() (or document.selected).

You could try to set up document wide event handlers for mousedown and mouseup. On mousedown you store the element under the pointer and on mouseup you check if there is a selection.

The next step would be to generate the path to that element. That is also quite tricky.

Jonas Elfström
"What if the selection spans several DOM elements, what would the path be?" - That's a very good point. I didn't think about it. But as of now, I can assume that the user will only select the text inside a node.
Sudar