Skip to content

Instantly share code, notes, and snippets.

@bobisme
Created November 13, 2024 14:31
Show Gist options
  • Save bobisme/9a17709ed2d40efcd3cdc52cae28249b to your computer and use it in GitHub Desktop.
Save bobisme/9a17709ed2d40efcd3cdc52cae28249b to your computer and use it in GitHub Desktop.
Get a selector for any given DOM element.
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