title: Add a class to one and only one element from an HTML list on click
body: <p>I have a list like so:</p>
  <pre><code> &lt;ul&gt;
     &lt;li class=&quot;item&quot;&gt;Item 1&lt;/li&gt;
     &lt;li class=&quot;item&quot;&gt;Item 2&lt;/li&gt;
     &lt;li class=&quot;item&quot;&gt;Item 3&lt;/li&gt;
   &lt;/ul&gt;
  </code></pre>
  <p>And I need to add the class active to each item individually and remove it on the previous item on click.</p>
  <p>Something similar to this question <a href="https://stackoverflow.com/questions/61075567/vanilla-js-remove-class-from-previous-selection">Vanilla JS remove class from previous selection</a> however I need to use For loop instead of ForEach due to old browser compatibility.</p>
  <p>I've been trying to adapt that answer to my example:</p>
  <pre><code>const items = document.querySelectorAll(&quot;.item&quot;);
  
  for (let i = 0; i &lt; items.length; i++) {
    const item = items[i];
    item.addEventListener(&quot;click&quot;, addActiveClass);
  
    for (let i = 0; i &lt; items.length; i++) {
      const item = items[i];
      item.addEventListener(&quot;click&quot;, removeClass);
    }
  }
  
  function removeClass(e) {
    e.target.classList.remove(&quot;active&quot;);
  }
  
  function addActiveClass(e) {
    e.target.classList.add(&quot;active&quot;);
  }
  </code></pre>
  <p>But it's still not working as expected :(</p>