Created
June 28, 2016 19:18
-
-
Save balbuf/514e41b50c39ee0a0b9ff927f656d4e2 to your computer and use it in GitHub Desktop.
Add a "getXPath" method to the prototype for HTML element nodes
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
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