Created
February 21, 2016 11:52
-
-
Save fogrew/de31f06d0004e5675895 to your computer and use it in GitHub Desktop.
Get XPath for node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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