Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Geting reference to many elements having the same id using Javascript

Suppose to have the following:

<div>
   <div id="element"></div>
   <div id="element"></div>
   <div id="element"></div>
   <div id="element"></div>
   <div id="element"></div>
   <div id="element"></div>
   <div id="element"></div>
</div>

Ok. This html piece is placed somewhere in the code... I must collect all tags having the element id.

How can I achieve this in javascript?

getElementById allows me to retrieve only one element...

Furthermore I cannot give you other hypothesis... I mean I cannot rely on class parameter and on name parameter (I mean they all are divs, so...).

Thank you

like image 818
Andry Avatar asked Sep 16 '26 17:09

Andry


2 Answers

It's invalid to have more than one element with the same ID -- you should rethink your design so that you can assign unique IDs to each DIV.

If you still want to do it (but please don't), you can assign the outer DIV an ID and get a list of all children DIV like this:

var list = document.getElementById('outerDiv').getElementsByTagName('div');
like image 84
casablanca Avatar answered Sep 19 '26 07:09

casablanca


You can get all the divs like this

var alDivs = document.getElementById("element").parentNode.getElementsByTagName("div");
like image 22
Zaje Avatar answered Sep 19 '26 06:09

Zaje