1

Possible Duplicate:
record and retrieve html element / node path using javascript

I am trying to find the absolute path of a node in javascript.

basically a user select some text i fine its parent node and I am trying to find the absolute path to it so i could use it later on in xpath to locate the selected text again:

You can find an example of what i am talking about (in php) here:

xpath finding absolute path is there any easy way?

also by absolute path i mean something like : "/html/body/div[1]/div[1]/div[2]/span[2]"

here is what i have so far:

if (window.getSelection){
    t = window.getSelection();
    if (t.rangeCount > 0) {
         parent = t.getRangeAt(0).startContainer.parentNode
     } 
} else if (document.selection) {
    t = document.selection.createRange().text;
    range = document.selection.createRange();
    range.collapse(isStart);
    parent = document.selection.createRange().parentElement();
}  

if (t != '' && parent!='')   {
// here i would like to get the path
}

I've tried to solve the problem its seems i manage to get the tags parent/child order correct however there is some problem when i count the siblings it gives me complete nonsense or i am missing something.

Here is what i came up with so far:

function absolutePath(node) {
var tages = new Array();
var index = new Array();
var c = 0;
do {
    var k=1, e=node;
    while (e = e.previousSibling) {
        k++;
    }
    index[c] = k;
    tages[c] = node.nodeName;

    c++;
}while(node = node.parentElement)

//alert(tages + '\n' + index);
return path;
}

Any input will be greatly appreciated

Community
  • 1
  • 1
Neta Meta
  • 4,001
  • 9
  • 42
  • 67
  • That does not return what i was looking for.i guess there is no simple way to do it and will have to recursion this one. – Neta Meta Dec 24 '12 at 01:01
  • Earlier I pointed you to a pure XSLT solution. You may use it "as-is" or you may translate it to Javascript. – Dimitre Novatchev Dec 24 '12 at 01:43
  • ah just saw it.I've never used XSLT - i don't really know what it is to be honest. will it be better to learn or work on a something that will do it in JS ? – Neta Meta Dec 24 '12 at 01:52

0 Answers0