Last active
June 24, 2024 17:05
-
-
Save iimos/e9e96f036a3c174d0bf4 to your computer and use it in GitHub Desktop.
Micro function that gives xpath by element and elements by xpath.
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 xpath(el) { | |
if (typeof el == "string") return document.evaluate(el, document, null, 0, null) | |
if (!el || el.nodeType != 1) return '' | |
if (el.id) return "//*[@id='" + el.id + "']" | |
var sames = [].filter.call(el.parentNode.children, function (x) { return x.tagName == el.tagName }) | |
return xpath(el.parentNode) + '/' + el.tagName.toLowerCase() + (sames.length > 1 ? '['+([].indexOf.call(sames, el)+1)+']' : '') | |
} | |
// Usage: | |
// Getting xpath for node: | |
var xp = xpath(elementNode) | |
// Executing xpath: | |
var iterator = xpath("//h2") | |
var el = iterator.iterateNext(); | |
while (el) { | |
// work with element... | |
el = iterator.iterateNext(); | |
} |
Works great! Thank you so much
ps: as xpath isn't truly unique, got any thoughts on making it unique?
I'm thinking something like... combining xpath + href + css selectors to make a unique generated ID etc.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why is the iterator needed? Shouldn't the function always lead to a single element?
BTW, thanks for this amazing piece of cake! It is working good so far.