Use multiple conditions with querySelectorAll in JavaScript

avatar

Borislav Hadzhiev

Last updated: Dec 28, 2021

banner

Check out my new book

Use multiple conditions with querySelectorAll #

To use multiple conditions with the querySelectorAll method, pass multiple, comma-separated selectors to the method, e.g. document.querySelectorAll('div.box1, span.box3'). The method will return a NodeList that contains the elements that match the specified group of selectors.

Here is the html for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box1">Box 1</div> <div class="box2">Box 2</div> <span class="box3">Box 3</span> <p class="box4">Box 4</p> <span id="box5">Box 5</span> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const elements1 = document.querySelectorAll('div.box1, span.box3'); console.log(elements1); // 👉️ [div.box1, span.box3] const elements2 = document.querySelectorAll('div, span, p'); console.log(elements2); // 👉️ [div.box1, div.box2, span.box3, p.box4] const elements3 = document.querySelectorAll('div.box1, span#box5'); console.log(elements3); // 👉️ [div.box1, span#box5]

We passed multiple unrelated selectors to the document.querySelectorAll method.

The method takes one or more selectors as a parameter.

Note that when passing multiple selectors, they must be separated using commas.

The first example selects all div elements with a class of box1 and all span elements with a class of box3.

index.js
const elements1 = document.querySelectorAll('div.box1, span.box3');

The second example selects all div, span and p elements and returns them in the same NodeList.

index.js
const elements2 = document.querySelectorAll('div, span, p');

The third example selects all div elements with a class of box1 and a span element with an id of box5.

index.js
const elements3 = document.querySelectorAll('div.box1, span#box5');

Note that the querySelectorAll method returns a NodeList, not an array. This means that you can't use most of the methods the array data type implements.

If you want to convert the result to an array, use the Array.from method.

index.js
const elements1 = Array.from(document.querySelectorAll('div.box1, span.box3')); console.log(elements1); // 👉️ [div.box1, span.box3]

After the NodeList is converted to an array, you can use any of the array-supported methods in JavaScript.

Here is an example that uses the Array.forEach method to iterate over the array of DOM elements.

index.js
const elements1 = Array.from(document.querySelectorAll('div.box1, span.box3')); console.log(elements1); // 👉️ [div.box1, span.box3] elements1.forEach(element => { console.log(element); });
Use the search field on my Home Page to filter through my more than 3,000 articles.