Why and when for loop ignore some item with html collection

后端 未结 2 531
渐次进展
渐次进展 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:04

    The problem here is that you are using document.getElementsByClassName which gives you a live NodeList. You should use document.querySelectorAll('.test') instead.

    var newtest = document.querySelectorAll('.test');
    for (var i=0; i < newtest.length; i++) {
        newtest[i].className = "bob";
    }
    

    With live NodeList collection newtest is a reference to a dynamically updated collection of elements (indexed by className test). So after the first loop iteration when you overwrite className with bob the whole collection becomes smaller by one (because newtest[0] no longer has class test). It makes indices shift.

    One more problem with your code: don't forget var keywords.

    Demo: http://codepen.io/anon/pen/BAFyb

提交回复
热议问题