item 1
  • item 2
  • item 3In a click, I...">

    Active state management

    <ul> <li><a href="#">item 1</a></li> <li><a href="#">item 2</a></li> <li><a href="#">item 3</a></li> </ul> 

    In a click, I would like to add addclass active to the parent li element, and also remove the active class from any other element that may already be active.

    +6
    javascript jquery
    source share
    2 answers
     $("li a").click( function() { $(".active").removeClass("active"); $(this).parent("li").addClass("active"); }); 
    +6
    source share
     $('div.filter').delegate('a', 'click', function (event) { var theLi = $(this).closest('li'); theLi.siblings('.active:first').removeClass('active'); theLi.addClass('active'); $('ul.items li').hide().filter('.' + this.href.slice(this.href.indexOf("#") + 1)).show(); event.preventDefault(); }); 
    +2
    source share

    All Articles