views:

63

answers:

2

How to colorize even (or odd) table columns using jQuery? (without adding classes manually)

My markup is:

<table>
   <caption>Table caption</caption>
   <thead>
   <tr><th scope="col">Table header 1</th><th scope="col">Table header 2</th><th scope="col">Table header 3</th><th scope="col">Table header 3</th></tr>
   </thead>
   <tbody>

        <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr>
        <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr>
        <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr>

        <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr>
   </tbody>
</table>

(it may or may not contain scope attribs or th tags)

+4  A: 

You can use the :nth-child() selector for this:

$('table tr :nth-child(2n)').css('background-color', '#eee');

You can see a demo here, this version does the columns, regardless if the cell is a <th> or <td> you can add that in there (e.g. td:nth-child(2n)) if you want to do only one or the other. If you want to select the other columns, just do 2n+1 instead. ​

Nick Craver
+1: Thanks for your comment in my answer and providing the right solution here.
Sarfraz
Thanks, this one works fine (previous version did some kind of checkers ;)
Adrian
Need more rep to upvote :)
Adrian
Is this possible without JS? CSS3 only?
Adrian
Worth noting here that I don't think this will work if you have anything rowspanned in your table since the second child will no longer be the second column.
Chris
Thanks for the link to [jsfiddle.net](http://jsfiddle.net) too, I didn't know this tool.
Adrian
@Chris, yes, for simplest markup from my question this is OK. Any solution for rowspanned tables?
Adrian
@Adrian - Yep, CSS3 only: http://jsfiddle.net/mYuHR/7/
Nick Craver
@Nick, This is really nice. Wondering which up-to-date browsers supports this syntax already.
takeshin
+1  A: 

Edit: Updated to fix my misreading of the question.

This should work:

$('tr > :nth-child(even)').css('background-color','#eee');

or

$('tr > :nth-child(odd)').css('background-color','#eee');
Ken Redler
Ken - OP is coloring columns, not rows. :o)
patrick dw
@patrick: Oops, you're right.
Ken Redler
This one is coloring rows, I need *columns*
Adrian
Yup, thanks. Fixed it.
Ken Redler
Ken - You're neglecting the `th` elements that the OP said may or may not be present. :o)
patrick dw
Thanks Patrick, updated yet again.
Ken Redler