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 Serve Static Files with Nginx and Docker
How to deploy a PHP app using Docker
How to deploy a Deno app using Docker
Getting Started with Deno
How to deploy a MySQL Server using Docker
How to deploy a Node app using Docker
Using Puppeteer and Jest for End-to-End Testing
Getting User Location using JavaScript's Geolocation API
Getting Started with Moment.js
Creating a Twitter bot with Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
Setting Up Stylus CSS Preprocessor
