Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: highlight even columns (not rows)

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)

like image 546
Adrian Avatar asked Jul 06 '10 15:07

Adrian


2 Answers

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. ​

like image 195
Nick Craver Avatar answered Oct 14 '22 17:10

Nick Craver


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');
like image 23
Ken Redler Avatar answered Oct 14 '22 18:10

Ken Redler