Categories
JavaScript Answers

How to Use document.getElementById with Multiple IDs in JavaScript?

Spread the love

Sometimes, we want to use document.getElementById with Multiple IDs in JavaScript

In this article, we’ll look at how to use document.getElementById with Multiple IDs in JavaScript

Use document.getElementById with Multiple IDs in JavaScript

To use document.getElementById with Multiple IDs in JavaScript, we can replace document.getElementById with document.querySelector.

For instance, if we have:

<div id='myCircle1'>
  circle
</div>
<div id='myCircle2'>
  circle
</div>
<div id='myCircle3'>
  circle
</div>
<div id='myCircle4'>
  circle
</div>

Then we write:

const circles = document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4")
console.log(circles)

We call document.querySelectorAll with a string that has the selector of all the elements separated by a comma.

And then we assign the returned result to circles.

Therefore, circles is a node list with the 4 elements we selected.

Conclusion

To use document.getElementById with Multiple IDs in JavaScript, we can replace document.getElementById with document.querySelector.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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