Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gpittarelli/5689979e69eec0f3d76d202c835f3bd0 to your computer and use it in GitHub Desktop.
Save gpittarelli/5689979e69eec0f3d76d202c835f3bd0 to your computer and use it in GitHub Desktop.
Simple browser xpath helpers
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