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
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!