Reputation: 31
I'm learning Javascript and I can't seem to figure out why the following code does not work. It will change the background of the first paragraph, but not the second one. When I check the console, it looks like the access variable is only returning one item to the array. Any suggestions? Thanks.
HTML
<p class="blue">Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>
<p class = "blue">Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>
CSS:
.blue{
background: blue;
}
.orange{
background:orange;
}
Javascript:
var access = document.getElementsByClassName("blue");
for(var i = 0; i<access.length; i++){
access[i].className = "orange";
}
Upvotes: 3
Views: 2406
Reputation: 318182
You're getting a live nodeList, meaning the collection will update as the DOM changes.
When you change the classname inside the loop, one element no longer matches the selector .blue
and the length is suddenly 1
and not 2
, so the loop ends before it reaches the second element.
When iterating over live nodeLists, one should generally iterate in reverse
var access = document.getElementsByClassName("blue");
for (var i = access.length - 1; i > -1; i--) {
access[i].className = "orange";
}
Or you could you use a method that gets you a non-live nodeList instead, like document.querySelectorAll('.blue')
Upvotes: 6