- An element with an id attribute
- An element without the id attribute
- An element with the id attribute but should not be used
It’s pretty easy to get the selector for an element with browser developer tools.
Then you can paste it to somewhere you need it. The selector value looks like this:
1 | #wikiArticle > ul:nth-child(14) |
The question is: How can we get the selector of an element using JavaScript?
An element with an id attribute
1 | const getCssPath = element => { |
An element without the id attribute
1 | const getCssPath = element => { |
An element with the id attribute but should not be used
An element may have the id
attribute but we don’t know if its value is valid. So we could ignore its id attribute and use the long version selector instead:
1 | const getCssPath = (element, ignoreID = false) => { |