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
: 3851 At:- 5/29/2020 11:15:45 AM
jQuery add remove class jquery







2 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


profileImage Answered by:- bhanu

If you want to toggle class, or remove class you can also do it using Javascript ( without jquery)

Toggle Class JS based

<button class="red btn" type="button" id="btn"  onclick="changeColor()">Click Me to toggle class</button>

Javascript

function changeColor() {
     document.getElementById("btn").classList.toggle('red');
     document.getElementById("btn").classList.toggle('green');
}

Replace/Add Class using Pure Javascript

 function changeColor() {
const btn = document.querySelector('#btn');

// print existing classes
console.log(btn.className); // 

// add new class
btn.className += 'btn';

// replace all existing classes
btn.className = 'red btn';
}

You can check detailed article here "Toggle or Replace Class (Javascript based, without jQuery)"

1
At:- 5/8/2021 9:32:26 AM






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