I'm trying to add a class [active] when I click on a element in my menu. Then remove that class [active] when I click on a new item in the menu and add the [active] class to it.
I've tried $(this).removeClass("active").addClass("active");
$(this).toggleClass("active");
Basically i'm trying to make the hover() function but with the click even.
Edit: Fixed HTML
<ul class="menu">
<li><span>Three</li>
<li><span>Two</li>
<li><span>One</li>
</ul>
The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.
To add a class on click of anchor tag, we use addClass() method. The addClass() method is used to add more property to each selected element. It can also be used to change the property of the selected element.
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're all siblings, you can use this:
$(this).addClass('active').siblings('.active').removeClass('active');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With