Get multiple elements by Id using JavaScript
To select elements by multiple Ids using JavaScript we have to use document.querySelectorAll() method instead getElementById() method in JavaScript.
In this short tutorial, we will learn how to select multiple elements by their Ids in JavaScript.
To select multiple elements by its ids , we cannot use document.getElementById method. Instead we have to use the document.querySelectorAll() method.
Why we need document.querySelectorAll() ?
The document.querySelectorAll() method returns a static NodeList of all the document's elements that matches the specified group of selectors.
Syntax:
querySelectorAll(selectors)
The selectors can be id or class names of document elements.
So let's see an example to select multiple document elements by their ids.
Here is the HTML for our page.
<body> <div id="one">One</div> <div id="two">Two</div> <div id="three">Three</div> <script src="main.js"></script> </body>
We have three <div> with ids one, two and three.
To select all three elements by their id, we will use the document.querySelectorAll() method in our script like this.
const mydivs = document.querySelectorAll("#one, #two, #three"); console.log(mydivs)
This will give us a NodeList of the selected elements in our console.

This NodeList contains three elements we have selected.
Once we got our selected elements we can add CSS style or add event listeners to it.
Here we will add CSS style to change the color of the text of the selected elements.
const mydivs = document.querySelectorAll("#one, #two, #three"); mydivs.forEach((element) => { element.style.color = "red"; });
Result:

We have looped through each element in the NodeList using forEach() and added the text color red using element.style.color = "red" .
Demo(Full Code):
<a href="https://codesandbox.io/s/eloquent-haslett-ewjimt?fontsize=14&hidenavigation=1&theme=dark"> <img alt="Edit ewjimt" src="https://codesandbox.io/static/img/play-codesandbox.svg"> </a>Related Posts
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
in vs hasOwnProperty(): Differences in Inherited Properties
The article explains the differences between JavaScript's 'in' operator and 'hasOwnProperty()' method. And also learn the use cases of both in JS.
How to Fix "ReferenceError: document is not defined" in JavaScript
The "ReferenceError: document is not defined" is a common error in JavaScript that occurs when trying to access the `document` object in a non-browser environment like Node.js.
How to Fix the "Cannot Read Property of Undefined" Error in JavaScript
The "Cannot read property of undefined" error occurs when you try to access a property or method of a variable that is undefined in JavaScript.
