Skip to content

Instantly share code, notes, and snippets.

@mholtzhausen
Last active November 19, 2019 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mholtzhausen/b8c60882b23b87f41c202df72a8f364d to your computer and use it in GitHub Desktop.
Save mholtzhausen/b8c60882b23b87f41c202df72a8f364d to your computer and use it in GitHub Desktop.
XPATH in the browser
function Elem2Xpath(elt) {
function getElementIdx(elt) {
let count = 1;
for (let sib = elt.previousSibling; sib; sib = sib.previousSibling) {
if (sib.nodeType == 1 && sib.tagName == elt.tagName)
count++
}
return count;
}
let path = "";
for (; elt && elt.nodeType == 1; elt = elt.parentNode) {
idx = getElementIdx(elt);
xname = elt.tagName;
if (idx > 1)
xname += "[" + idx + "]";
path = "/" + xname + path;
}
return path;
}
function Xpath2Elem(xpath) {
return document.evaluate(
xpath,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment