Skip to content

Instantly share code, notes, and snippets.

@x4d3
Forked from karlgroves/gist:7544592
Last active July 31, 2021 19:19
Show Gist options
  • Save x4d3/fd39936f966da5e22f2a642ce6fb8c72 to your computer and use it in GitHub Desktop.
Save x4d3/fd39936f966da5e22f2a642ce6fb8c72 to your computer and use it in GitHub Desktop.
Get DOM path of an element
const getDomPath = node => {
const stack = [];
let el = node;
while (el.parentNode != null) {
let siblingCount = 0;
let siblingIndex = 0;
for (let i = 0; i < el.parentNode.childNodes.length; i += 1) {
const sib = el.parentNode.childNodes[i];
if (sib.nodeName === el.nodeName) {
if (sib === el) {
siblingIndex = siblingCount;
}
siblingCount += 1;
}
}
if (el.hasAttribute("id") && el.id !== "") {
stack.unshift(`${el.nodeName.toLowerCase()}#${el.id}`);
} else if (siblingCount > 1) {
stack.unshift(`${el.nodeName.toLowerCase()}:eq(${siblingIndex})`);
} else {
let nodeName = el.nodeName.toLowerCase();
if (el.className) {
const classes = el.className.trim().split(" ").join(".");
nodeName = `${nodeName}.${classes}`;
}
stack.unshift(nodeName);
}
el = el.parentNode;
}
return stack.slice(1).join(" > "); // removes the html element
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment