Skip to content

Instantly share code, notes, and snippets.

@sayhicoelho
Created May 20, 2020 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sayhicoelho/f8f26455956aa2877ca778e5086fe12a to your computer and use it in GitHub Desktop.
Save sayhicoelho/f8f26455956aa2877ca778e5086fe12a to your computer and use it in GitHub Desktop.
Get element CSS selector using JS
// ref: https://stackoverflow.com/a/57503796/4158755
// Thanks to Yassine!
function getCssSelector(el) {
const names = []
do {
let index = 0
let cursorElement = el
while (cursorElement !== null) {
++index
cursorElement = cursorElement.previousElementSibling
}
names.unshift(el.tagName + ':nth-child(' + index + ')')
el = el.parentElement
} while (el !== null)
return names.join(' > ')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment