The problem is that the NodeList returned to you is "live" - it changes as you alter the class name. That is, when you change the class on the first element, the list is immediately one element shorter than it was.
Try this:
while (elementArray.length) {
elementArray[0].className = "exampleClassComplete";
}
(There's no need to use setAttribute()
to set the "class" value - just update the "className" property. Using setAttribute()
in old versions of IE wouldn't work anyway.)
Alternatively, convert your NodeList to a plain array, and then use your indexed iteration:
elementArray = [].slice.call(elementArray, 0);
for (var i = 0; i < elementArray.length; ++i)
elementArray[i].className = "whatever";
As pointed out in a comment, this has the advantage of not relying on the semantics of NodeList objects. (Note also, thanks again to a comment, that if you need this to work in older versions of Internet Explorer, you'd have to write an explicit loop to copy element references from the NodeList to an array.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…