The following javascript code does not work correctly. (I am using IE9 and cannot use a different browser or JQuery):

var elems = document.getElementsByClassName("EditableTextBox");
for (var i = 0; i < elems.length; i++) {                
    elems[i].className = "Zero";
}

What happens is, only SOME elements with className "EditableTextBox" are changed to className "Zero", many remain with className "EditableTextBox". There is no further code that could be causing this issue; this code is the last bit of code I execute before the screen is refreshed.

I thought the problem was with .getElementsByClassName not finding all the correct elements, however:

var elems = document.getElementsByClassName("EditableTextBox");
for (var i = 0; i < elems.length; i++) {                
    elems[i].value = "test";
}

This code DOES change the value of ALL the correct elements to "test", so .getElementsByClassName DOES find all the elements correctly.

I do not understand what is causing the problem here. My way around this is below, but can anyone with more experience here please explain why the first block of code is not working? Thank you.

My Workaround in case anyone is interested:

var elems = document.getElementsByTagName("input");
for (var i = 0; i < elems.length; i++) {
    if (elems[i].className == "EditableTextBox")
       elems[i].className = "Zero";

Thank you.

有帮助吗?

解决方案

The getElementsByClassName seems to return a live set, so when you change the class of any item the set gets updated immediately, and it will skip each other item. Do the loop in reverse instead:

for (var i = elems.length - 1; i >= 0; --i) {                
    elems[i].className = "Zero";
}

其他提示

An alternative would be:

while(list.length!=0) {
    list[0].className = 'Zero';
}

That way you know you can't miss an element.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top