Created
November 13, 2024 14:31
-
-
Save bobisme/9a17709ed2d40efcd3cdc52cae28249b to your computer and use it in GitHub Desktop.
Get a selector for any given DOM element.
This file contains hidden or 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 = (element) => { | |
const path = []; | |
let currentElement = element; | |
while (currentElement) { | |
let selector = currentElement.tagName.toLowerCase(); | |
// Add id if it exists | |
if (currentElement.id) { | |
selector += `#${currentElement.id}`; | |
} else { | |
// Add classes if no id | |
const classes = Array.from(currentElement.classList).join('.'); | |
if (classes) { | |
selector += `.${classes}`; | |
} | |
// Add position among siblings if no unique identifier | |
if (!currentElement.id && (!classes || currentElement.tagName.toLowerCase() === 'div')) { | |
const siblings = Array.from(currentElement.parentNode?.children || []); | |
const similarSiblings = siblings.filter(sibling => | |
sibling.tagName === currentElement.tagName | |
); | |
if (similarSiblings.length > 1) { | |
const index = similarSiblings.indexOf(currentElement) + 1; | |
selector += `:nth-of-type(${index})`; | |
} | |
} | |
} | |
path.unshift(selector); | |
currentElement = currentElement.parentElement; | |
} | |
return path.join(' > '); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment