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