Created
May 20, 2020 18:24
-
-
Save sayhicoelho/f8f26455956aa2877ca778e5086fe12a to your computer and use it in GitHub Desktop.
Get element CSS selector using JS
This file contains 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
// 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