Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
getUniqueSelector — Return a unique selector for a specific element (151 bytes minified, 144 bytes gzipped)
/** Return a unique selector for a specific element. */
let getUniqueSelector = (/** @type {Element} */ element) => {
/** Unique selector for this element */
let selector = ''
/** @type {Element} */
let parent
/** @type {number} */
let nth
while (parent = element.parentElement) {
for (nth = 1; element = element.previousElementSibling; ++nth);
selector = ' > :nth-child(' + nth + ')' + selector
element = parent
}
return ':root' + selector
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment