Get multiple elements by Id using 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.

nodelist of multiple elements selected by id

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:

change text color of multiple id

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):

Edit ewjimt

💾 Recommended Articles