3

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";
}
1
  • Use document.querySelectorAll('.blue') instead. It doesn't return a live node list like getElementsByClassName does and you won't get that issue. Commented Apr 15, 2016 at 18:35

1 Answer 1

6

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')

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for helping me understand this. I got it working and tried your other suggestion, using querySelectorAll('.blue'). I can't get it to work: var access2 = document.querySelectorAll(".blue"); for(var i = 0; i<access2.length; i++){ access2[i].className = ".orange"; }
@trustIsEarned - remove the period, it should be access2[i].className = "orange"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.