First, sorry for my bad English...
I wrote a function to change the class of elements to change their properties. For some reason, only some of the elements have changed, it took me a few hours to find a solution, but he seems odd to me, perhaps you can explain to me.
function replace(){
var elements = document.getElementsByClassName('classOne');
for (var i=0; i<elements.length;i++) {
elements[i].className = 'classTwo';
}
}
not working as well, Demo here, [on chrome 25 and FF], So I took the loop coefficient:
function replace(){
var elements = document.getElementsByClassName('classOne');
for (var i=0; i<elements.length;i) { //----here the different --- i without ++
elements[i].className = 'classTwo';
}
}
This works well! seems as 'push' called, and no coefficient needed... It is normal? It is different from the examples I've seen.
Thanks in advance!
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.
getElementsByClassName
returns a NodeList. A NodeList collection is a live collection, which means that the modification of the document affects the collection. more
Or revert the loop, beginning by length-1 and step down to 0
来源:https://stackoverflow.com/questions/15562484/getelementsbyclassname-strange-behavior