Skip to content

Instantly share code, notes, and snippets.

@curtisz
Last active November 10, 2015 17:45
Show Gist options
  • Save curtisz/af21f6cb9cb32ff418f0 to your computer and use it in GitHub Desktop.
Save curtisz/af21f6cb9cb32ff418f0 to your computer and use it in GitHub Desktop.
Get Element XPath
var getElementXPath = function(element) {
if (element && element.id) {
// has id, so use it instead of full xpath
return '//' + element.nodeName.toLowerCase() + '[@id="' + element.id + '"]';
} else {
// gets absolute xpath
return getElementTreeXPath(element);
}
};
var getElementTreeXPath = function(element) {
var paths = [];
// Use nodeName (instead of localName) so namespace prefix is included (if any).
for (; element && element.nodeType == 1; element = element.parentNode) {
var index = 0;
for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) {
// Ignore document type declaration.
if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) continue;
if (sibling.nodeName == element.nodeName) ++index;
}
var tagName = element.nodeName.toLowerCase();
var pathIndex = ('[' + (index+1) + ']');
paths.splice(0, 0, tagName + pathIndex);
}
return paths.length ? '/' + paths.join('/') : null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment