Skip to content

Instantly share code, notes, and snippets.

@ademilter
Created December 15, 2019 18:29
Show Gist options
  • Select an option

  • Save ademilter/9396af93c609264a939d2df5fa2e6b15 to your computer and use it in GitHub Desktop.

Select an option

Save ademilter/9396af93c609264a939d2df5fa2e6b15 to your computer and use it in GitHub Desktop.
selected node get xpath
function getXPath(nodeElem) {
const parts = [];
while (nodeElem && nodeElem.nodeType === Node.ELEMENT_NODE) {
let nbOfPreviousSiblings = 0;
let hasNextSiblings = false;
let sibling = nodeElem.previousSibling;
while (sibling) {
if (
sibling.nodeType !== Node.DOCUMENT_TYPE_NODE &&
sibling.nodeName === nodeElem.nodeName
) {
nbOfPreviousSiblings++;
}
sibling = sibling.previousSibling;
}
sibling = nodeElem.nextSibling;
while (sibling) {
if (sibling.nodeName === nodeElem.nodeName) {
hasNextSiblings = true;
break;
}
sibling = sibling.nextSibling;
}
const prefix = nodeElem.prefix ? nodeElem.prefix + ":" : "";
const nth =
nbOfPreviousSiblings || hasNextSiblings
? `[${nbOfPreviousSiblings + 1}]`
: "";
parts.push(prefix + nodeElem.localName + nth);
nodeElem = nodeElem.parentNode;
}
return parts.length ? "/" + parts.reverse().join("/") : "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment