0

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>
divakar
  • 63
  • 8
  • This should help > https://stackoverflow.com/questions/507138/how-do-i-add-a-class-to-a-given-element . Scroll down in the same page, you should see answers for removing class as well. – Jaikanth S Oct 11 '18 at 05:44
  • What language/template engine/framework is that? – connexo Oct 11 '18 at 06:20

3 Answers3

1

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>
RedPandaz
  • 2,618
  • 2
  • 9
  • 16
0

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.

Sam Gomena
  • 951
  • 4
  • 17
0

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)

Amir Fawzy
  • 419
  • 5
  • 10