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!
- Managing PHP Dependencies with Composer
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Sass
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue
- How To Create a Modal Popup Box with CSS and JavaScript