Reading timeยท2 min
Use the querySelectorAll()
method to select elements by multiple ids, e.g.
document.querySelectorAll('#box1, #box2, #box3')
.
The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.
Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <div id="box1">Box 1</div> <div id="box2">Box 2</div> <div id="box3">Box 3</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const boxes = document.querySelectorAll('#box1, #box2, #box3'); // ๐๏ธ [div#box1, div#box2, div#box3] console.log(boxes);
We passed multiple, comma-separated selectors to the
document.querySelectorAll method to get
a NodeList
of the elements with IDs box1
, box2
and box3
.
If none of the selectors matches an element, an empty NodeList
is returned.
SyntaxError
exception is thrown.If you have an array of IDs and need to get a collection of the elements with these IDs, use this approach instead.
const ids = ['box1', 'box2', 'box3']; const boxes = document.querySelectorAll( ids.map(id => `#${id}`).join(', ') ); // ๐๏ธ [div#box1, div#box2, div#box3] console.log(boxes);
The function we passed to the Array.map() method gets called with each ID in the array.
The map()
method returns a new array containing the values returned from the
callback function.
The last step is to join the array of IDs into a string with a comma separator.
If you need to iterate over the NodeList
, use the
NodeList.forEach
method.
const boxes = document.querySelectorAll('#box1, #box2, #box3'); // ๐๏ธ [div#box1, div#box2, div#box3] console.log(boxes); boxes.forEach(box => { console.log(box); });
The function we passed to the forEach
method gets called for each element in
the NodeList
.
Note that you can't use all of the native array methods on the NodeList
.
If you need to perform more complex operations on the collection, use the
Array.from
method to convert it to an array.
const boxes = Array.from( document.querySelectorAll('#box1, #box2, #box3') ); // ๐๏ธ [div#box1, div#box2, div#box3] console.log(boxes); // ๐๏ธ true console.log(Array.isArray(boxes));
The Array.from method takes an array-like object and converts it to an array.
You can also use the spread syntax (...) to convert the NodeList
to an array.
const boxes = [...document.querySelectorAll('#box1, #box2, #box3')]; // ๐๏ธ [div#box1, div#box2, div#box3] console.log(boxes); // ๐๏ธ true console.log(Array.isArray(boxes));
The spread syntax (...) unpacks the elements of the NodeList
into an array
which enables us to use any array methods on the collection.
You can learn more about the related topics by checking out the following tutorials: