Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Last active July 14, 2023 16:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/4e16d61511def15999a027feaf8ce5ac to your computer and use it in GitHub Desktop.
Save jonathantneal/4e16d61511def15999a027feaf8ce5ac to your computer and use it in GitHub Desktop.
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