Toggling only a single class as active in a list with vanilla JS or CSS Every time I toggle active class in a list (to dynamically change DOM content) I find that I always go to this approach to check and clear which class is active. I'm still fairly new to using pure javascript so I'm wondering if there is a better, simpler approach?

It feels like having to run a second function to clear out all active classes seems grunty. 

I've included an example of how I do it.



var specialNav = document.getElementById("special-nav");

if (specialNav) {
  var navItems = specialNav.getElementsByTagName('li');
  var i;
  for (i = 0; i &lt; navItems.length; i++) {
    navItems[i].addEventListener("click", function() {
      if (!this.classList.contains('active')) {
        clearActives(navItems);
        this.classList.toggle('active');
      }
    });
  }
}

function clearActives(classlist) {
  if (classlist) {
    for (i = 0; i &lt; classlist.length; i++) {
      classlist[i].classList.remove('active');
    }
  }
}
.active {
  color: red
}

li {
  cursor: pointer;
}
&lt;div id="special-nav"&gt;
  &lt;ul&gt;
    &lt;li class="active"&gt; 1&lt;/li&gt;
    &lt;li&gt;2&lt;/li&gt;
    &lt;li&gt;3&lt;/li&gt;
    &lt;li&gt;4&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
Another approach could be with hidden radio inputs and :checked CSS selector :



input { display: none }
input:checked ~ * { color: red }
&lt;label&gt;&lt;input type="radio" name="li" checked&gt;&lt;li&gt;1&lt;/li&gt;&lt;/label&gt;
&lt;label&gt;&lt;input type="radio" name="li"&gt;&lt;li&gt;2&lt;/li&gt;&lt;/label&gt;
&lt;label&gt;&lt;input type="radio" name="li"&gt;&lt;li&gt;3&lt;/li&gt;&lt;/label&gt;
&lt;label&gt;&lt;input type="radio" name="li"&gt;&lt;li&gt;4&lt;/li&gt;&lt;/label&gt;