santa
santa

Reputation: 12512

New row count after each TH

I have a table with a few rows with and a few ones with following. Is there a way to apply style to the TDs as in odd/even restarting after every row with THs with jQuery?

<table>
<tr>
  <th>header 1</th>
</tr>
<tr>
  <td>123</td>
</tr>
<tr>
  <td>445</td>
</tr>
<tr>
  <td>7899</td>
</tr>
<tr>
  <th>header 2</th>
</tr>
<tr>
  <td>asd</td>
</tr>
<tr>
  <td>ddd</td>
</tr>
<tr>
  <td>ggg</td>
</tr>
</table> 

Upvotes: 3

Views: 172

Answers (2)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79840

Try something like below,

DEMO: http://jsfiddle.net/Tvyfz/2/

$(function () {
   var zc = 0;

   $('table tr').each (function (idx, el) {
      if ($(el).find('th').length != 0) {
         zc = 0;
      } else {
         $(el).addClass((++zc%2)?'even':'odd');
      }

   });
});

Note: Your markup didn't had a proper closing </tr>

Edit: minor cleanup.

Upvotes: 3

Steve Robbins
Steve Robbins

Reputation: 13822

var i = 0;

$('table tr').each(function() {

    if ($(this).is(':has(th)')) return i = 0;    
    $(this).children().addClass(i++ % 2 ? 'odd' : 'even');
});​

http://jsfiddle.net/u9hjA/

Upvotes: 4

Related Questions