- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › 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:
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!