سؤال

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