views:

917

answers:

4

jQuery has the handy :even and :odd selectors for selecting the even- or odd-indexed items in a set, which I'm using to clear every other item in a series of floated boxes, as follows:

<div class='2up'>
   <div> ... </div>
   <div> ... </div>
   ...
   <div> ... </div>
</div>

and

// Clear every 2nd block for 2-up blocks
$('.2up>div:even').css("clear", "both");

This works like a charm.

My question: Is there a straightforward way in jQuery to select every third or fourth item, so I could do the same thing with 3-up or 4-up items?

+6  A: 

You could use the :nth-child(index/even/odd/equation) selector. http://docs.jquery.com/Selectors/nthChild#index

Chris Gutierrez
A: 

No, not as such. The filter function will let you do that though.


EDIT:

I stand corrected. Use the n-th child function for simplicity.

Sean Vieira
+6  A: 

Try:

$("div:nth-child(3n+1)").css("clear", "both");
loviji
`:nth-child` is also standard CSS3, whereas `:odd` is a jQuery/Sizzle-only extension that won't work in your stylesheets.
bobince
+1  A: 

you can use the :nth-child(index/even/odd/equation) selector.

Example:

<div class='5up'>
   <div> ... </div>
   <div> ... </div>
   ...
   <div> ... </div>
</div>
and
// Clear every 5th block for 5-up blocks
$('.5up>div:nth-child(5n)').css("clear", "both");
or
// Clear after every 5th block for 5-up blocks
// note: This will also clear first block.
$('.5up>div:nth-child(5n+1)').css("clear", "both");

alexanderpas
FWIW: Since it's zero-based, `(5n)` clears before the 5th block and every 5th following, so you end up with 4 blocks in the first row and 5 in following rows. `(5n+1)` works perfectly.
Herb Caudill