Add and remove a class on click using jQuery?

angela picture angela · Oct 22, 2013 · Viewed 199.7k times · Source

Please see this fiddle.

I am trying to add and remove a class on li elements that are clicked. It is a menu and when one clicks on each li item I want it to gain the class and all other li items have the class removed. So only one li item has the class at a time. This is how far I have got (see fiddle). I am not sure how to make the 'about-link' start with the class current, but then it is remove when one of the other li items are clicked on?

$('#about-link').addClass('current');
$('#menu li').on('click', function() {
    $(this).addClass('current').siblings().removeClass('current');
});

Answer

Jamie Taylor picture Jamie Taylor · Oct 22, 2013

Why not try something like this?

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

JSFiddle