How to use querySelectorAll() with Multiple Classes in JavaScript

Updated onbyAlan Morel
How to use querySelectorAll() with Multiple Classes in JavaScript

JavaScript has several built-in methods available for you to when you want to query the DOM for elements.

One of the most useful methods is querySelectorAll() which allows you to query the DOM for elements based on a CSS selector.

However, you can also use querySelectorAll() to query the DOM for elements with multiple classes.

In this post, we'll learn how to use querySelectorAll() to select elements in the DOM with multiple classes.

How to use querySelectorAll() to query for elements with multiple classes

As mentioned before, querySelectorAll() allows you to query the DOM for elements based on a CSS selector.

The "all" part means it will return an array containing all the elements that match the CSS selector.

Here's an example:

<ul>
    <li class="list-item">Item 1</li>
    <li class="list-item">Item 2</li>
    <li class="list-item">Item 3</li>
</ul>
const listItems = document.querySelectorAll(".list-item");

listItems.forEach(listItem => {
    console.log(listItem.textContent);
});
Item 1

As you can see, querySelectorAll() returned an array containing all the elements with the class list-item.

Since querySelectorAll() uses CSS selectors, you can also use it to query for elements with multiple classes.

To do this, make use of what is called a CSS selector group.

Let's say you wanted to target all the list items with the class list-item and the class inactive.

<ul>
    <li class="list-item active">Item 1</li>
    <li class="list-item inactive">Item 2</li>
    <li class="list-item inactive">Item 3</li>
</ul>
const listItems = document.querySelectorAll(".list-item.inactive");

listItems.forEach(listItem => {
    console.log(listItem.textContent);
});
Item 2
Item 3

By passing in the selector group .list-item.inactive, querySelectorAll() returned an array containing all the list items with the classes list-item and inactive, just like you would style this using CSS.

Here's an example of how you would style those elements using the same CSS selector group:

.list-item.inactive {
    color: red;
}

Here's the full example:

  • HTML
  • CSS
  • JavaScript

Conclusion

In this post, we learned how to use querySelectorAll() to query the DOM for elements with multiple classes.

This is useful for when you want to be more specific when querying the DOM for elements.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.