简体   繁体   中英

changing className issue (javascript and IE)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM