The problem is that getElementsByClassName
returns a NodeList
, which is a live collection. Thus, every time you asked for its length, the collection is recalculated. Since you have already changed the className for some elements, the loop ends earlier than you expected.
If you check the values for i
and length
for each loop, you will have:
- The first time, length is 3. (0 < 3) is true, so it changes its class.
- The second time, length is 2. (1 < 2) is true, so it changes its class.
- The first time, length is 1. (2 < 1) is false. It doesn't change its class.
You should convert the NodeList to an array:
var e = [].slice.call(document.getElementsByClassName("hidden"));
Or you can use the alternative code you provided, although in that case the selection is recalculated every time you ask for its length property.