GirkovArpa
GirkovArpa

Reputation: 4942

How to use CSS selector in JavaScript to find element that includes a specific class?

The correct way to give an element multiple classes is simply put spaces between them. Right?

Then why does the selector [class=CLASSNAME] not work unless it's the only class?

[class^=CLASSNAME] works if the class is the first one.

But how to select all elements that possess a given class, regardless of the number or order of their classes?

I want to select all the elements with class foo-bar. But the code below only selects the first one.

const selector = '[class=foo-bar]';
const divs = document.querySelectorAll(selector);
console.log([...divs].map(div => div.textContent));
<div class="foo-bar">foo</div>
<div class="foo-bar baz">bar</div>
<div class="baz foo-bar">baz</div>

Upvotes: 0

Views: 35

Answers (1)

Barmar
Barmar

Reputation: 782683

When you use an attribute selector, it's matching against the entire attribute value as an ordinary string. It doesn't treat the class attribute specially, so it's not considered to be a list of classes that can be matched individually.

Just as in CSS, use .classname to match any class in the list.

const selector = '.foo-bar';
const divs = document.querySelectorAll(selector);
console.log([...divs].map(div => div.textContent.trim()));
<div class="foo-bar">foo</div>
<div class="foo-bar baz">bar</div>
<div class="baz foo-bar">baz</div>

Upvotes: 3

Related Questions