tags:

views:

58

answers:

3

Hello

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

+4  A: 

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

Gaby
FYI, should be idx==10 not 1
Scott
@scott, it should be 9 because it is zero-based, but you are correct. I had messed the numbers in my answer.. updated. thanks.
Gaby
Oh yes, of course :-)
Scott
Yep, this works very well, I went with Patrick's answer as it seems a simpler solution, but this worked just as well for me. But thanks for this solution, very appreciated
Dave
+4  A: 

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');
});
patrick dw
i like this version!
choise
+1, i like this too (plus i used `or` instead of `||` in mine, and just saw it while looking at your answer)
Gaby
@Gaby - I didn't even notice that you had `or`! :o) If you're doing minor corrections though, you have `addclass` instead of `addClass`. I figured OP would get the overall point. :o)
patrick dw
@patrick, good spotting. thanks :)
Gaby
This works very well for me, thanks very much Patrick, excellent stuff!
Dave
@Dave - You're welcome. :o)
patrick dw
+2  A: 
$(".thumbnail:eq(4), .thumbnail:eq(9)").addClass("last");
$(".thumbnail:gt(9)").addClass("bottom-last");
Alexis Abril
Same again, this works very well, thanks a lot!
Dave