-
-
Save x4d3/fd39936f966da5e22f2a642ce6fb8c72 to your computer and use it in GitHub Desktop.
Get DOM path of an element
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
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