I am currently using this code to add a class to every other row in my table.
$(".stripeMe tr:even").addClass("alt");
However, on another table I'd like to add a class to rows 3,4, 7,8, 11,12 and so on...
Is this possible?
I am currently using this code to add a class to every other row in my table.
$(".stripeMe tr:even").addClass("alt");
However, on another table I'd like to add a class to rows 3,4, 7,8, 11,12 and so on...
Is this possible?
With the `:nth-child´ selector: http://api.jquery.com/nth-child-selector/
$(".stripeMe tr:nth-child(4n), .stripeMe tr:nth-child(4n-1)").addClass("alt");
You need to do it like this:
$(".stripeMe tr:nth-child(4n)").add(".stripeMe tr:nth-child(4n-1)").addClass("alt");
//or...
$("tr:nth-child(4n), tr:nth-child(4n-1)", ".stripeMe").addClass("alt");
You can see this working here.
Using this:
$(".stripeMe tr:nth-child(4n), .stripeMe tr:nth-child(4n-1)").addClass("alt");
gets different results (namely in webkit, possibly others).
You can use the filter
function to filter the set any way you like:
$(".stripeMe tr")
.filter(function(i){ return (i % 4) >= 2; })
.addClass("alt");
This will keep the items with index 2, 3, 6, 7, 10, 11 and so on. Note that the index is zero based, so the third row as index two.
just a fizz buzz like! ;-)
$('.stripeMe tr').each(function(i) {
if ( (i % 4) >= 2 )
$(this).addClass('alt');
});
keep: 3,4, 7,8 11,12
I made a different approach for this problem using a for loop and .eq() method.
var a = 2; // start from 2 because eq() counts from 0
var b = 3; // start from 3 because eq() counts from 0
var total = $('.stripeMe td').length;
for (i = 0; i <= total; i++){
if (i == a){
$('.stripeMe tr:eq('+a+')').css('background', 'red');
a+=4;
}
else if (i == b){
$('.stripeMe tr:eq('+b+')').css('background', 'blue');
b+=4;
}
};