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>
2
  • This should help > stackoverflow.com/questions/507138/… . Scroll down in the same page, you should see answers for removing class as well. Commented Oct 11, 2018 at 5:44
  • What language/template engine/framework is that? Commented Oct 11, 2018 at 6:20

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

It would be better if you add HTML markup in the code snippet!
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.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.