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)
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.
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');
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With