简体   繁体   中英

How to add and remove active class using js

This is my menu html How can i add active class and remove active class using js :

<div class="sidenav">
    <a  href="{{url('/home')}}" class="sidemenu"><i class="fa fa-home"></i> 
    </br>Users</a>
    <a href="{{route('user-channel.index')}}" class="sidemenu"><i class="fa 
    fa-plus"></i></br>Channel</a>
</div>

Something like this should work.

 var sideNav = document.querySelector(".sidenav"); sideNav.addEventListener("click", function(e) { e.stopPropagation(); e.preventDefault(); if (e.target.classList.contains("sidemenu")) { for (let i = 0; i <= sideNav.children.length - 1; i++) { if (sideNav.children[i].classList.contains("active")) { sideNav.children[i].classList.remove("active"); } } e.target.classList.add("active"); } }); 
 .active { color: blue; background-color: yellow; } a { text-decoration: none; } 
 <div class="sidenav"> <a href="" class="sidemenu"><i class="fa fa-home"></i> </br>Users</a> <a href="" class="sidemenu"><i class="fa fa-plus"></i></br>Channel</a> </div> 

In short, use something like this:

// Get element
var element = document.getElementById("sidenav");

// Add class
element.classList.add("active");

// Remove class
element.classList.remove("active");

Follow up here for more info.

this how you can do it.

const linkList = document.querySelectorAll('.sidemenu');
const link = document.querySelector('.sidemenu');

link.addEventListener('click', e => {
  let $this = e.target;
  linkList.forEach(ele => {
    ele.classList.remove('active');
  });
  $this.classList.add('active');
});

javascript interpreter in browser read script from top to bottom so first we get the list of items have calss .sidemenu by declaring consistent variable linkList then we get the one element node by declaring another consistent variable link after we make click event inside we declare variable $this to refer to the event target (the element i have clicked) then we make loop on all links that have .sidemenu class to remove class active then out side the loop and in event block we add active class to the target (the element i have just clicked)

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