简体   繁体   中英

How to add/remove active class in Bootstrap4

I am trying to add/remove active class in the navbar using a snipped from similar questions, however nothing happens in my case. It´s very possible I am missing out something that could not figured out so far.

Here is my HTML

<div class="collapse navbar-collapse" id="navbarColor01">
  <ul class="navbar-nav mr-auto">
    <li class="nav-item active" id="dashboard">
      <a class="nav-link" href="{% url 'dashboard' %}">Dashboard</a>
    </li>
    <li class="nav-item" id="painel_regras">
      <a class="nav-link" href="{% url 'painel_regras' %}">Todos as Regras</a>
    </li>
  </ul>
</div>

Here is the Javascript part

<script type="text/javascript">
  var navContainer = document.getElementById("navbarColor01");
  var navitem = navContainer.getElementsByClassName("nav-item");
  for (var i = 0; i < navitem.length; i++) {
    navitem[i].addEventListener("click", function() {
      var current = document.getElementsByClassName("active");
      current[0].className = current[0].className.replace(" active", "");
      this.className += " active";
    });
  }
</script>

There might be conflicts with other elements that have the active class, so when you access current[0] , the item at index 0 is not the one in the navbar. I have replaced document.getElementsByClassName with document.querySelector to make the element more specific.

 var navContainer = document.getElementById("navbarColor01"); var navitem = navContainer.getElementsByClassName("nav-item"); for (var i = 0; i < navitem.length; i++) { navitem[i].addEventListener("click", function() { var current = document.querySelector("#navbarColor01 .nav-item.active"); current.className = current.className.replace(" active", ""); this.className += " active"; }); }
 .active { font-weight: bold; }
 <div class="collapse navbar-collapse" id="navbarColor01"> <ul class="navbar-nav mr-auto"> <li class="nav-item active" id="dashboard"> <a class="nav-link" href="#">Dashboard</a> </li> <li class="nav-item" id="painel_regras"> <a class="nav-link" href="#">Todos as Regras</a> </li> </ul> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM