Getting CSS selector of an element

  1. An element with an id attribute
  2. An element without the id attribute
  3. 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.

Chrome Developer Tool

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
2
3
4
const getCssPath = element => {
const id = element.getAttribute('id');
return id ? '#' + id : '';
};

An element without the id attribute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const getCssPath = element => {
const tags = [];
while (element.parentNode) {
if (element.id) {
tags.unshift('#' + element.id);
break;
} else {
if (element === document.body) {
tags.unshift('body');
break;
} else {
let c = 1;
// we use variable `c` to hold the value of the index
for (let e = element; e.previousElementSibling; e = e.previousElementSibling, c++);
tags.unshift(element.tagName.toLowerCase() + ':nth-child(' + c + ')');
}
element = element.parentNode;
}
}
return tags.join(' > ');
};

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const getCssPath = (element, ignoreID = false) => {
const tags = [];
while (element.parentNode) {
if (element.id && !ignoreID) {
tags.unshift('#' + element.id);
break;
} else {
if (element === document.body) {
tags.unshift('body');
break;
} else {
let c = 1;
// we use variable `c` to hold the value of the index
for (let e = element; e.previousElementSibling; e = e.previousElementSibling, c++);
tags.unshift(element.tagName.toLowerCase() + ':nth-child(' + c + ')');
}
element = element.parentNode;
}
}
return tags.join(' > ');
};