Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change class names in JavaScript

Tags:

javascript

I have a simple menu in HTML:

<ul id="menu">
    <li><a id="admin" onclick="changeActive('admin');" class="active a red">Admin</a></li>
    <li><a id="dash" onclick="changeActive('dash');" class="a black">Dash</a></li>
    <li><a id="notifs" onclick="changeActive('notifs');" class="a black">Notifs</a></li>
</ul>

The idea is to change the active element dynamically.

My current function is:

function changeActive(id)
    {
      document.getElementById(id).className += "active a red";
      var c = document.querySelectorAll("ul a");
      for (i in c)
      {
        fav = c[i].attributes[0];
        if(fav.value!=id)
          {
            console.log(fav.value);
            document.getElementById(fav.value).className += "a black";
          }
      }
    }

Is there a more efficient solution to this? Thanks!

like image 566
Arjun Avatar asked Mar 25 '17 07:03

Arjun


3 Answers

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";
}
like image 52
Hari Lamichhane Avatar answered Oct 06 '22 01:10

Hari Lamichhane


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

  document.getElementById(id).classList.add("active a red");
like image 37
Sagar V Avatar answered Oct 06 '22 01:10

Sagar V


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>
like image 42
gavgrif Avatar answered Oct 05 '22 23:10

gavgrif