9

Possible Duplicate:
Combining jQuery :not and :nth-child selectors

is this possible?

Here is my code:

$("ul#filterlist li:nth-child(3n)").css("marginTop", "0");

If I wanted to apply that to the list, but only to those items VISIBLE in the list (some get hidden, I don't want them counted), how would it be achieved? I was thinking something like:

$("ul#filterlist li:nth-child(3n)").not(":hidden").css("marginTop", "0");

But it won't work. Neither will anything I try with :visible

Any ideas? Thanks.

Community
  • 1
  • 1
Phill
  • 546
  • 1
  • 5
  • 16
  • It's not a duplicate of :not, as :not wasn't apart of the solution, it was just the way I thought it would logically work, in which it didn't, thanks – Phill Oct 26 '12 at 08:02

3 Answers3

15

The method you're looking for is filter(). It will filter down a list of jQuery objects based on the given selector. Since there was no "not :hidden" selector I could found, I used the opposite :visible.

$("ul#filterlist li:nth-child(3n)").filter(":visible").css("marginTop", "0");

Hope this helps!

vtsatskin
  • 325
  • 2
  • 7
2

If you don't want to count the hidden elements you can try using the following code.

$("ul#filterlist li:visible").filter(function(index){ 
    return (index+1)%3 == 0?true:false;
}).css("marginTop", "0");

see the example in jsfiddle here

Tamillharasan
  • 460
  • 4
  • 10
1

try chaining the :selectors

$("ul#filterlist li:nth-child(3n):not(:hidden)").css("marginTop", "0");

like shown in this answer:

jQuery - multiple :not selector

Community
  • 1
  • 1
WebChemist
  • 4,393
  • 6
  • 28
  • 37