changing className issue (javascript and IE)

三世轮回 提交于 2019-12-11 02:06:17

问题


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.


回答1:


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";
}



回答2:


An alternative would be:

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

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



来源:https://stackoverflow.com/questions/16335527/changing-classname-issue-javascript-and-ie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!