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
First, the below code should do the trick in the simplest way.
var blockSet = document.getElementsByClassName("block-default").className = "block-selected";
Next what goes wrong with your code, or rather what is the interesting thing that is happening:
blockSet[0].className = 'block-selected';
makes the first block set element no longer a block set element. That leaves you with 7 remaining. Now,
blockSet[1].className = 'block-selected';
Selects the second one of the remaining ones. Which would be the third one of your complete list. Now you have 6 remaining.
blockSet[2].className = 'block-selected';
This makes the third one among the remaining, which would be your BLOCK5 into a block selected. And results in you having 5 remaining.
blockSet[3].className = 'block-selected';
This again finds your fourth one which is BLOCK7 when you count to the fourth among your remaining. And now you have 4 remaining.
blockSet[4] onwards find no such element and fail to execute. This is what happens with your code. Quite interesting. :).
Here is a jsfiddle alerting you the values as they run: https://jsfiddle.net/xz7h57jv/