className only changing every other class

后端 未结 15 2230
陌清茗
陌清茗 2020-12-01 23:41

I\'m performing a small text with JavaScript with the getElementsByClassName() and I am getting some unwanted results. I would like the script to change each CS

15条回答
  •  情书的邮戳
    2020-12-02 00:17

    This error occurs because blockSet is an HTMLCollection, which is "live." HTMLCollections update as the elements on the page update.

    Every time you swap a className, you're making blockSet shorter one by one.

    To solve this problem, just do this instead:

    for (var i = 0; i < 8; i += 1) {
        blockSet[ 0 ].className = "block-selected";
    }
    

    That way you chunk your HTMLCollection off one by one.

    Iteration 1: [ div1, div2, div3, div4, div5, div6, div7, div8 ]

    Iteration 2: [ div2, div3, div4, div5, div6, div7, div8 ]

    Iteration 3: [ div3, div4, div5, div6, div7, div8 ]

    Iteration 4: [ div4, div5, div6, div7, div8 ]

    Iteration 5: [ div5, div6, div7, div8 ]

    Iteration 6: [ div6, div7, div8 ]

    Iteration 7: [ div7, div8 ]

    Iteration 8: [ div8 ]

    Hope that helps!

提交回复
热议问题