Dave
Dave

Reputation: 716

Count child DIVs + add class

I have the following bit of code to display thumbnails on a page:

<div id="gallery"> <div class="thumbnail"> <img src="" /> </div> </div>

This will loop to show 15 .thumbnail DIVs.

I would like to attach a class of ".last" to the 5th DIV and the 10th DIV. And for the 11-15th DIVs a class of ".bottom-last".

I understand that this is the way to go: http://api.jquery.com/length/ but cannot figure out a way to get the count and then attached the class.

Any pointers?

Thanks a lot

Upvotes: 1

Views: 1552

Answers (3)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196306

use the each method which passes the index as a parameter..

$('#gallery .thumbnail').each( function(idx){
if (idx==4 || idx==9)
  $(this).addClass('last');
if (idx > 9)
  $(this).addClass('bottom-last');
} );

note the numbers are 1 minus what you want, because the index is zero-based

Upvotes: 4

Alexis Abril
Alexis Abril

Reputation: 6469

$(".thumbnail:eq(4), .thumbnail:eq(9)").addClass("last");
$(".thumbnail:gt(9)").addClass("bottom-last");

Upvotes: 2

user113716
user113716

Reputation: 322622

Here's one way if you don't mind the syntax. (of course, you could easily use a traditional if() statement as well)

Try it out: http://jsfiddle.net/bBgTs/1/

$('#gallery .thumbnail').addClass(function(i) {
    return ((i == 4 || i == 9) && 'last') || (i > 9 && 'bottom-last');
});

Upvotes: 4

Related Questions