[JAVASCRIPT] getElementByID() is not getting all tagged elements
YatinBayya (18)

When you change a style of a certain ID, javascript is only picking up the first div

<div id="myID" style="width:100px;height:100px;"></div>
<div id="myID" style="width:100px;height:100px;"></div>
<div id="myID" style="width:100px;height:100px;"></div>

In javascript

document.getElementByID("myId").style.backgroundColor="red";

If anyone can help me that would be appriciated

You are viewing a single comment. View All
vedprad1 (731)

This is because every element must have a unique ID. Think about what ID means. It is used to identify unique objects.

Let's put this into a school analogy. Every student has his or her unique student ID. However, groups of students have common classes.

If you want to have multiple divs to be targetted, you shouldn't use id, you should use class. Here is the HTML:

<div class="myClass" style="width:100px;height:100px;"></div>
<div class="myClass" style="width:100px;height:100px;"></div>
<div class="myClass" style="width:100px;height:100px;"></div>

And here is the javascript:

var arr = document.getElementsByClassName("myClass");
for (var i = 0; i < arr.length; i++) {
  arr[i].style.backgroundColor = "red";
}

If this answers your question, please check the checkmark on the left side of this message. Thanks and Good Luck!

YatinBayya (18)

@vedprad1 but when you say getElementByClassName() it is actually a list so you need to loop through it