Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Zebra selector

Tags:

jquery

I have a CSS class called grid which I place on my tables. I want to Zebra strip my even rows so I use the following jQuery code

$(".grid tr:nth-child(even)").addClass("even");

This basically says "Apply the css class even to any tr tag which has a parent (at any level) with a class of grid." The problem with this is when I have nested tables, the child table's tr tags will also get the even style. Since I did not specify the child table with a class of grid, I don't want it to pick up the zebra stripe.

How can I specify to only apply the even class on tr tags which are a direct descendant of the tag which has the grid class?

like image 713
Bob Avatar asked Nov 13 '08 16:11

Bob


2 Answers

You want to use a different selector, like the child selector:

$(".grid > tr:nth-child(even)").addClass("even");

This limits the selection to direct children your .grid only.

like image 83
MrKurt Avatar answered Oct 14 '22 14:10

MrKurt


There's a great jQuery blog post that you might find useful: Zebra Table Showdown.

This post also includes an interesting discussion of how to do zebra striping in most of the other major JavaScript libraries.

Scroll down to see comments on adding hover effects to your zebra striping using jQuery.

like image 30
dshaw Avatar answered Oct 14 '22 14:10

dshaw