Dynamically change class names in JavaScript

Notice I removed += so that you donot end up adding same class every time.

function changeActive(id) {
      var c = document.querySelectorAll("ul a");
      var i;
      for (i in c) {
        c[i].className = 'a black';
      }
      //update it at last
      document.getElementById(id).className = "active a red";
}

Use classList property and it's add method. remove will remove the class

  document.getElementById(id).classList.add("active a red");

With navmenus, you want to set the active state on the li and apply the style to the a within the active li.

The following has both the id, the active class and the onclick handler in the li ( as well as a fake href in the a) and functions to remove the active class from all li's on the click and then apply it to the selected li. The .active class CSS then colors the a in red.

function changeActive(option){
  var option = option;
  var li = document.getElementsByTagName("li");
  for(i=0;i<li.length;i++){
     li[i].classList.remove("active");
  }
  document.getElementById(option).classList.add("active");
}
ul{list-style:none}
a{color:black;text-decoration:none}
.active a{color:red}
<ul id="menu">
    <li class="active" onclick="changeActive('admin')" id="admin"><a  href="#">Admin</a></li>
    <li onclick="changeActive('dash')" id="dash"><a href="#">Dash</a></li>
    <li onclick="changeActive('notifs')" id="notifs"><a href="#">Notifs</a></li>
</ul>

Tags:

Javascript