BlueFire BlueFire - 1 year ago 88
Javascript Question

Javascript for loop suddenly breaks

I have the following problem.

I generate a list with all the elements with a specific class. After that i'm looping throug them to replace the class.

As you can see here: only one of the 2 elements get replaced. The console.log clearly shows that the loop only goes through once.
If I comment the 7 javascript code out. (See the fiddle) the loop works fine.

What did I do wrong?


var list = document.getElementsByClassName("default");
for(var i = 0; i < list.length; i++)

Answer Source

getElementsByClassName gets a live nodeList of all the elements with the class default, the nodeList updates as the elements change.

When you remove the class default, the length of the live nodeList changes, so when you start iterating at the start, for every element that has the class removed, the length decreases by 1.

When you get halfway, you've changed half the elements, and you're half way in the loop, and the length is just half, so it stops.

The solution is to iteratte in reverse

var list = document.getElementsByClassName("default");

for(var i=list.length; i--;) {

or get a non-live nodeList using querySelectorAll

var list = document.querySelectorAll(".default");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download