treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Adding class to LI w/ jQuery

  • 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:

    <script type="text/javascript" charset="utf-8">
    $(function () {
    var tabContainers = $('div#filter > div');
    tabContainers.hide().filter(':first').show();

    $('div#filter ul a').click(function () {
    tabContainers.hide();
    tabContainers.filter(this.hash).show();
    $('div#filter ul li').removeClass('on');
    $(this).addClass('on');
    return false;
    }).filter(':first').click();
    });
    </script>




    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
  • 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.

  • Thanks! The first method worked by adding ".parent().". I knew it was something super simple.!
  • Awesome!