How to add / remove class in jQuery dynamically on click?


I am trying to create a list of anchor tags, and want to add or remove CSS class on a button click, Suppose this is my sample code

<ul id="MainMenu">
<li><a href="" class="active">Link A </a></li>
<li><a href="">Link B</a></li>
<li><a href="">Link C</a></li>
</ul>

How do i change class "active" from "Link A" to "LInk B", if currently "Link A" has class. Basically want to add class "active" to the selected anchor tag on click.


Asked by:- neena
0
: 91 At:- 5/29/2020 11:15:45 AM
jQuery add remove class jquery






1 Answers
profileImage Answered by:- vikas_jk

You can simply use this jquery to add/remove class on click of anchor tag

$('#MainMenu li a').on('click', function(){
    $('#MainMenu li a.active').removeClass('active');
    $(this).addClass('active');
});

Take a look this sample fiddle: https://jsfiddle.net/ym9Lb7t3/

change-class-on-click-jquery-min.gif

If you don't want to remove class from previously selected anchor, use .toggleClass()

$('#MainMenu li a').on('click', function () {
    $(this).toggleClass('active')
});
1
At:- 5/30/2020 2:46:02 PM
Thanks for quick answer, works well for me. 0
By : neena - at :- 6/5/2020 3:41:08 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly