Last active
November 19, 2019 12:09
-
-
Save mholtzhausen/b8c60882b23b87f41c202df72a8f364d to your computer and use it in GitHub Desktop.
XPATH in the browser
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 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