J
Jeff
Hi all,
I'm wondering if there is a function that will return the xpath to a
specific node given its context node. Essentially, I want the reverse
of the document.evaluate functionality. I've seen examples where
people build up the xpath themselves by walking the DOM, but I thought
there has to be a better way. I've included a simple example of this,
based on code from the Solvent project at MIT. This code works
reasonably well, but can't always narrow down to a specific node when
the node doesn't have an id assigned.
Thanks!
Jeff
function getXPath(node, doc) {
var xpath = "";
var namespace = node.ownerDocument.documentElement.namespaceURI;
var prefix = namespace ? "x:" : "";
var node2 = node;
for(var i=0; node2 && node2 != doc; i++) {
var tag = node2.tagName.toLowerCase();
var id = node2.id;
var className = node2.className;
var segment = prefix + tag;
if (id && id != "") {
xpath = "//" + segment + '[@id="' + id + '"]' + xpath;
break;
}
xpath = "/" + segment + xpath;
node2 = node2.parentNode;
}
return xpath;
}
I'm wondering if there is a function that will return the xpath to a
specific node given its context node. Essentially, I want the reverse
of the document.evaluate functionality. I've seen examples where
people build up the xpath themselves by walking the DOM, but I thought
there has to be a better way. I've included a simple example of this,
based on code from the Solvent project at MIT. This code works
reasonably well, but can't always narrow down to a specific node when
the node doesn't have an id assigned.
Thanks!
Jeff
function getXPath(node, doc) {
var xpath = "";
var namespace = node.ownerDocument.documentElement.namespaceURI;
var prefix = namespace ? "x:" : "";
var node2 = node;
for(var i=0; node2 && node2 != doc; i++) {
var tag = node2.tagName.toLowerCase();
var id = node2.id;
var className = node2.className;
var segment = prefix + tag;
if (id && id != "") {
xpath = "//" + segment + '[@id="' + id + '"]' + xpath;
break;
}
xpath = "/" + segment + xpath;
node2 = node2.parentNode;
}
return xpath;
}