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!
Getting Started with TypeScript
Create an RSS Reader in Node
Git Tutorial: Learn how to use Version Control
How to Set Up Cron Jobs in Linux
How to build a Discord bot using TypeScript
Getting Started with Deno
Getting Started with Sass
Getting Started with Handlebars.js
Learn how to build a Slack Bot using Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
Setting Up Stylus CSS Preprocessor
Using Axios to Pull Data from a REST API
