Created
June 20, 2019 23:08
-
-
Save gpittarelli/5689979e69eec0f3d76d202c835f3bd0 to your computer and use it in GitHub Desktop.
Simple browser xpath helpers
This file contains hidden or 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* xpathLazy(q) { | |
const x = document.evaluate( | |
q, | |
document, | |
null, | |
XPathResult.UNORDERED_NODE_ITERATOR_TYPE, | |
null | |
); | |
let n = x.iterateNext(); | |
while (n) { | |
yield n; | |
n = x.iterateNext(); | |
} | |
} | |
function xpath(q) { | |
const all = [...xpathLazy(q)]; | |
return all.length > 0 ? all : null; | |
} | |
function lookup(sel) { | |
if (sel[0] === '/') { | |
const els = xpath(sel); | |
return els ? els[0] : null; | |
} else { | |
return document.querySelector(sel); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment