Select elements by Multiple IDs using JavaScript

avatar

Borislav Hadzhiev

Thu Jan 06 20222 min read

Select elements by Multiple IDs using JavaScript #

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 in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <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.

index.js
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.

The string you pass to the method must a valid CSS selector string. If it isn't, a SyntaxError exception is thrown.

If you have an array of ids and need to get a collection of the elements with those ids, use this approach instead.

index.js
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.

Whatever we return from the callback function gets included in the new array themap() method returns.

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, you can use the NodeList.forEach method.

index.js
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 do more complex operation on the collection, convert it to an array using the Array.from method.

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee