Why and when for loop ignore some item with html collection

后端 未结 2 529
渐次进展
渐次进展 2020-12-12 01:12

I attached a codepen example : http://codepen.io/anon/pen/zpmjJ

I just try to change the classname of an html collection array with a classic loop and after many tes

2条回答
  •  天涯浪人
    2020-12-12 02:09

    getElementsByClassName is live selector, so when you change something that not matching this selector, it will remove element from scope. So at first iteration it has 3 elements, but when you change class, it remove one element and you leave with 2 elements, so on next iteration it will take i element which is i=1 so it will take second element from top. That's why you get always 1 missing. You may use newtest[0].className="bob"; to loop through, but when you will reach last element, it will be single element, not array any more, so you need to use newtest.className="bob"; for last one

提交回复
热议问题