Javascript for loop suddenly breaks

I have the following problem.

I create a list with all elements with a specific class. After that, I loop them to replace the class.

As you can see here: https://jsfiddle.net/nafxLoLz/ only one of the two elements is replaced. The .log console clearly shows that the loop runs only once. If I comment on javascript code 7. (See Violin), the loop works fine.

What have I done wrong?

the code:

var list = document.getElementsByClassName("default");
console.log(list.length);
for(var i = 0; i < list.length; i++)
{
  console.log(i);
  list[i].classList.add("red");
  list[i].classList.remove("default");
}
+4
source share
3 answers

getElementsByClassNamegets live nodeList of all elements with the class default, nodeList is updated as the elements change.

default, live nodeList, , , , , 1.

, , , , .

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

for(var i=list.length; i--;) {
  list[i].classList.add("red");
  list[i].classList.remove("default");
}

, querySelectorAll

var list = document.querySelectorAll(".default");
+7

, , getElementsByClassName, "", , , .

. red default. default list. , 1, 1 .

+2

Try adding a different class name to the squares that will not be removed to help identify them:

<div class="square default">
</div>
<div class="square default">
</div>

And use the "square" as a class selector:

var list = document.getElementsByClassName("square");
console.log(list.length);
for(var i = 0; i < list.length; i++)
{
  console.log(i);
  list[i].classList.add("red");
  list[i].classList.remove("default");
}

Here is an example to demonstrate: https://jsfiddle.net/nafxLoLz/1/

+1
source

Source: https://habr.com/ru/post/1661880/


All Articles