What's going on is an odd side effect. When you reassign className
for each element of elements
, the element gets removed from the array! (Actually, as @ user2428118 points out, elements
is an array-like object, not an array. See this thread for the difference.) This is because it no longer has the classOne
class name. When your loop exits (in the second case), the elements
array will be empty.
You could write your loop as:
while (elements.length) {
elements[0].className = 'classTwo'; // removes elements[0] from elements!
}
In your first case, by incrementing i
, you are skipping half of the (original) elements that have class classOne
.
Excellent question, by the way. Well-researched and clear.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…