Jquery addclass / removeeclass when clicked

I am trying to add the [active] class when I click on an item in my menu. Then remove this [active] class when I click on the new item in the menu and add the [active] class to it.

I tried $(this).removeClass("active").addClass("active");

 $(this).toggleClass("active"); 

I am basically trying to make the hover () function, but with a click.

Edit: HTML fixed

 <ul class="menu"> <li><span>Three</li> <li><span>Two</li> <li><span>One</li> </ul> 
+7
source share
3 answers

Assuming only one active element at a time and without further knowledge of your DOM hierarchy.

 $('.active').removeClass('active'); $(this).addClass('active'); 

More efficient options are available if the DOM hierarchy is known.

For example, if they are all brothers and sisters, you can use this:

 $(this).addClass('active').siblings('.active').removeClass('active'); 
+17
source

Demo . Working example.

Fixed markup:

 <ul class="menu"> <li><span>Three</span></li> <li><span>Two</span></li> <li><span>One</span></li> </ul> 

Assuming LI tags should have an active class.

 <script> $('.menu li').on('click', function(){ $(this).addClass('active').siblings().removeClass('active'); }); </script> 
+9
source

Try this little library , can you switch the class with native JS? It will be like

 var menu = document.querySelector('.menu'); menu.addEventListener('click', function () { Elemental.toggleClass(this, 'active'); }) 

this will add or remove a class depending on its presence.

0
source

All Articles