Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop skips one after every other iteration

I have a list of HTML elements having class "black" (with some other classes). I want to convert the "black" to "white". I have written the following code.

var blacks = document.getElementsByClassName("black");
for (i = 0; i < blacks.length; i++)
    blacks[i].className = blacks[i].className.replace('black', 'white');

Interestingly, one element turns to white and one element is skipped until the end of elements. That is, elements with order of even numbers remain unchanged. What am I missing to convert all blacks?

like image 823
sevenkul Avatar asked Mar 04 '26 18:03

sevenkul


2 Answers

document.getElementsByClassName returns a live NodeList that is automatically updated as you make changes to part of DOM it represents. You are treating it like a static list. You can do that by converting it to array:

var blacks = [].slice.call(document.getElementsByClassName("black"));

It just occurred to me that you could also:

var blacks = document.querySelectorAll(".black"); //NodeList but static
like image 172
Esailija Avatar answered Mar 06 '26 07:03

Esailija


Further to the comment made about blacks being a live nodeList, you can avoid converting to an array, by simply decrementing through the loop:

var blacks = document.getElementsByClassName("black");
for (var i = blacks.length -1 ; i >= 0; --i) {
    blacks[i].className = blacks[i].className.replace('black', 'white');
}​

JS Fiddle demo.

like image 44
David Thomas Avatar answered Mar 06 '26 08:03

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!