Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The reason your original code failed is because <code>getElementsByClassName</code> returns a <strong>live view</strong> on the elements with the class <code>hidden</code>. Therefore, when you change the class of an element inside your loop, this change is reflected in the view and that element will no longer be in there.</p> <p>Here's an example scenario:</p> <ol> <li><code>e</code> initially contains 3 <code>hidden</code> elements.</li> <li>In the first iteration, <code>i == 0</code> and <code>e[0]</code> is changed to be <em>no longer</em> <code>hidden</code>. This means that <code>e</code> now only contains 2 <code>hidden</code> elements, as the 'old' <code>e[0]</code> is removed.</li> <li>In the second iteration, <code>i</code> is already at <code>1</code> but <code>e[0]</code> is <em>still</em> a <code>hidden</code> element. This means that you'll skip over <code>e[0]</code> (which was <code>e[1]</code> before the loop). In this iteration, you'll remove the class of <code>e[1]</code> (which was <code>e[2]</code> previously) and the view is reduced to 1 element.</li> <li>Since <code>i</code> (= 2) now exceeds <code>e.length</code> (= 1), the loop terminates.</li> </ol> <p>The net result is that you skipped over the old <code>e[1]</code>. There are two ways to tackle this problem:</p> <ul> <li>Make <code>e</code> static by copying its contents to another array first. This is the approach most libraries such as jQuery take.</li> <li>Make use of the <em>liveness</em>. As you showed in your edit, you can use the live collection to your advantage. By always operating on the <em>currently</em> first element in the view, you'll never skip over any element. The loop condition is also trivial: you just have to keep iterating until the view no longer contains any elements.</li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload