Skip to content

Instantly share code, notes, and snippets.

@fogrew
Created February 21, 2016 11:52
Show Gist options
  • Save fogrew/de31f06d0004e5675895 to your computer and use it in GitHub Desktop.
Save fogrew/de31f06d0004e5675895 to your computer and use it in GitHub Desktop.
Get XPath for node
[].forEach.call(document.getElementsByTagName('a'), function (link) {
console.log(getXPathForElement(link, document));
});
function getXPathForElement(el, xml) {
var xpath = '';
var pos, tempitem2;
while(el !== xml.documentElement) {
pos = 0;
tempitem2 = el;
while(tempitem2) {
if (tempitem2.nodeType === 1 && tempitem2.nodeName === el.nodeName) { // If it is ELEMENT_NODE of the same name
pos += 1;
}
tempitem2 = tempitem2.previousSibling;
}
xpath = "*[name()='"+el.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']["+pos+']'+'/'+xpath;
el = el.parentNode;
}
xpath = '/*'+"[name()='"+xml.documentElement.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']"+'/'+xpath;
xpath = xpath.replace(/\/$/, '');
return xpath;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment