Last updated: Mar 4, 2024
Reading timeยท2 min
To use multiple conditions with the querySelectorAll
method, pass multiple,
comma-separated selectors to the method.
The method will return a NodeList
that contains the elements that match the
specified group of selectors.
Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </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.
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.
The first example selects all div
elements with a class of box1
and all
span
elements with a class of box3
.
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
.
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
.
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.
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.
const elements1 = Array.from(document.querySelectorAll('div.box1, span.box3')); console.log(elements1); // ๐๏ธ [div.box1, span.box3] elements1.forEach(element => { console.log(element); });
You can learn more about the related topics by checking out the following tutorials: