Grow your CSS skills. Land your dream job.

Adding class to LI w/ jQuery

  • # February 1, 2011 at 2:51 pm

    I have this snippet of code that I am using to create a filter for WordPress categories and their posts. The thing is the links for changing the filter categories need to use 2 background images for the style I am creating. Here is the code I am using for the jQuery:

    So everything works fine, except, instead of applying the “on” class to the a element, I want to apply it to the li that is around the a. The original code is:

    $('div#filter ul a').removeClass('on');
    $(this).addClass('on');

    So, I had changed it to:

    $('div#filter ul li').removeClass('on');
    $(this).addClass('on');

    It is very successfully removing the “on” class from the li, but it isn’t adding back. I know this is something super simple to fix, but I just can’t figure it out. Any suggestions?

    -Lindsey

    # February 1, 2011 at 3:07 pm

    I think you’ll have to change

    $(this).addClass('on');

    to

    $(this).parent().addClass('on');

    If that won’t work try changing

    $('div#filter ul a').click(function () {

    to

    $('div#filter ul li').click(function () {

    since you want to bind the click event to the li instead of the a (maybe I’m wrong in assuming this?). In the current state of your code the “on” class probably gets added to the a inside the li? That’s because the click event is binded to the a element, so “this” will point to the a element.

    # February 1, 2011 at 3:20 pm

    Thanks! The first method worked by adding “.parent().”. I knew it was something super simple.!

    # February 1, 2011 at 3:25 pm

    Awesome!

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".