How to Use querySelectorAll() for Multiple Classes in the DOM

Published Jan 17, 2022  ∙  Updated May 2, 2022

How can we use querySelectorAll() to target multiple elements in the DOM?

Suppose we want to obtain instances of div and p tags.

CSS selectors

CSS supports what we call selector groups, which allows us to specify multiple selectors.

We might have seen this when applying the same CSS property to multiple elements in the DOM.

h1 { font-family: sans-serif }
h2 { font-family: sans-serif }
h3 { font-family: sans-serif }
/* Is equivalent to */
h1, h2, h3 { font-family: sans-serif }

This is also supported in querySelectorAll() because this function accepts all CSS selectors.

Any element we can target in CSS can be targeted in querySelectorAll().

querySelectorAll() with multiple elements

Per the example above, we can target div and p tags by targeting them how we would in a stylesheet.

const list = document.querySelectorAll("div, p");

As such, we can also target specific classes. For instance, we can target all div elements that have the class dog.

const list = document.querySelectorAll("div.dog");

We can also target all div elements containing a child element with class dog.

const list = document.querySelectorAll("div .dog");