In my opinion, the nth-child()
method suggested by @Arbel is preferable, but to make your question code work with a small modification, you can do the following:
$('.foo').each(function() {
if(!(($('.foo').index(this)-2) % 6)) {
$( this ).css( "background-color", "red" );
}
});
Essentially, what you want is every 6th element, starting from an offset of 2.
On a side note, the jQuery function 'each' actually passes in both the index and the element itself (native element) to the iterator function. So, you could rewrite the above code like this:
$('.foo').each(function(i,ele) {
if(!((i-2) % 6)) {
$(ele).css( "background-color", "red" );
}
});
EDIT
I mentioned that I preferred the nth-child
approach, however, considering some of the comments, using nth-of-type
may be more suitable for your needs.
For more information, check out these links:
Mozilla nth-of-type
and
CSS Tricks comparison of the two
Here's an example using nth-of-type
:
.foo:nth-of-type(6n-3)
{
background-color: red;
}
NOTE: The reason for the difference in the formula to determine the element you want (i.e. i-2 % 6 or 6n-3) is because JavaScript starts indexing at 0 as the first element, while CSS begins with 1 for the n in nth-child or nth-of-type selectors.