How to use querySelectorAll() with Multiple Classes in JavaScript
Table of Contents
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:
HTML<ul>
<li class="list-item">Item 1</li>
<li class="list-item">Item 2</li>
<li class="list-item">Item 3</li>
</ul>
JAVASCRIPTconst listItems = document.querySelectorAll(".list-item");
listItems.forEach(listItem => {
console.log(listItem.textContent);
});
HTMLItem 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
.
HTML<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>
JAVASCRIPTconst listItems = document.querySelectorAll(".list-item.inactive");
listItems.forEach(listItem => {
console.log(listItem.textContent);
});
BASHItem 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:
CSS.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!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with Moon.js