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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With