Languages

JavaScript - getElementById with multiple IDs

0 points
Asked by:
GamerGoals22
364

How can I get element handle by multiple IDs?

I want something like:

document.getElementById("myId1" "myId2" "myId3");
1 answer
0 points
Answered by:
GamerGoals22
364

You can use querySelectorAll() method. It allows to specify multiple ids in a CSS selector string.

Note:

getElementById() only supports one id at the time and returns a single node, not an array of nodes.

Practical example

// ONLINE-RUNNER:browser;

<html>
<body>
  <div id="id1">element1</div>
  <div id="id2">element2</div>
  <div id="id3">element3</div>
  <script>

    var handles = document.querySelectorAll("#id1, #id2, #id3");

    for(var i = 0; i < handles.length; ++i) {
        console.log(handles[i].outerHTML); // do something with the elements (e.g display their outerHTML)
    }

  </script>
</body>
</html>

 

See also

  1. JavaScript - get element handle by id

References

  1. Document.querySelectorAll() - Web APIs | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join