Skip to content

Instantly share code, notes, and snippets.

@balbuf
Created June 28, 2016 19:18
Show Gist options
  • Save balbuf/514e41b50c39ee0a0b9ff927f656d4e2 to your computer and use it in GitHub Desktop.
Save balbuf/514e41b50c39ee0a0b9ff927f656d4e2 to your computer and use it in GitHub Desktop.
Add a "getXPath" method to the prototype for HTML element nodes
window.HTMLElement.prototype.getXPath = function() {
// special cases
if (this.id) return '//*[@id="' + this.id + '"]';
if (this.tagName.toLowerCase() === 'html') return '/html';
var count = 0, index, nodes = this.parentNode.childNodes;
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].nodeType !== 1 || nodes[i].tagName !== this.tagName) continue;
count++;
if (nodes[i] === this) index = count;
}
return this.parentNode.getXPath() + '/' + this.tagName.toLowerCase() + (count > 1 ? '[' + index + ']' : '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment