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?
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?
Share Improve this question asked Jul 3, 2012 at 18:13 sevenkulsevenkul 9661 gold badge8 silver badges14 bronze badges 1-
1
Don't forget to declare "i" with
var
! – Pointy Commented Jul 3, 2012 at 18:17
2 Answers
Reset to default 8document.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 ment 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.