Get multiple elements by Id using JavaScript

featured Image

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

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *