views:

343

answers:

2

I can style every 4th 'item' div like so

  jQuery(".item:nth-child(4n)").addClass("fourth-item");

and that works fine, but then I hide some items, show some others and want to re-do this styling, but only styling every 4th item that is visible. So I have a function that will remove this styling and reapply it, but I need to specify in the reapplying of the style that it is only every 4th visible item, not every 4th item. I know the ":visible" selector but can't seen to chain it with the nth-child selector properly, any ideas?

I've tried various things like this to no avail...

jQuery(".item").removeClass("fourth-item");
jQuery(".item:visible:nth-child(4n)").addClass("fourth-item");
+2  A: 

:nth-child scans the children of the parent no matter what their styling is. The counting in :nth-child is relative to the parent element, not the previous selector. This is explained in the jQeury docs for :nth-child:

With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class.

Using a more simple method with each does exactly what you want:

$('#test li:visible').each(function (i) {
    if (i % 4 == 0) $(this).addClass('fourth-item');
});
Emil Ivanov
thanks, think that should actually be (i+1)%4 though :)
mbehan
Well, it depends! Note that `nth-child` is `1` based, while here `i` is `0` based.
Emil Ivanov
A: 

I'm trying to get this working with:

$(this).fadeIn('slow').removeClass('hidden').addClass("show");

                $('.portfolio:visible').each(function (i) {
                    if (i % 2 == 0) $(this).addClass("last");   
                });

Simply trying to add the .last class to visible portfolio items with the dynamic class .show

Any ideas?

Ian Jamieson