Dave
Dave

Reputation: 1057

JQuery alternate colors of *groups of rows* in a table

I have a table with multiple TBODY elements (one for each month in a year) and would like to alternate row colors within the TBODY element.

For illustration, I have a table with the following basic structure:

<table>
  <tbody>
    <tr>
      <th>October</th>
      <th>Total</th>
    </tr>
    <tr>
      <td>Item 1</td>
      <td>500</td>
    </tr>
    <tr>
      <td>Item 2</td>
      <td>1000</td>
    </tr>
    <tr>
      <td>Item 3</td>
      <td>1400</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <th>November</th>
      <th>Total</th>
    </tr>
    <tr>
      <td>Item 1</td>
      <td>800</td>
    </tr>
    <tr>
      <td>Item 2</td>
      <td>400</td>
    </tr>
    <tr>
      <td>Item 3</td>
      <td>200</td>
    </tr>
  </tbody>
  ... a <tbody> for all 12 months ...
</table>

And the following JQuery call:

<script type="text/javascript">
    $(function () {
        $("table > tbody > tr:even").addClass("alternate-row");
    });
</script>

But what happens is JQuery treats the entire table as one logical group and applies the alternate-row class to every odd row regardless of TBODY location.

In other words, what I want is:

October (normal color)
  Item #1 (normal color)
  Item #2 (alt color)
  Item #3 (normal color)
November (normal color)
  Item #1 (normal color)
  Item #2 (alt color)
  Item #3 (normal color)
... etc

Instead what I'm getting with the above JQuery is:

October (alt color)
  Item #1 (normal color)
  Item #2 (alt color)
  Item #3 (normal color)
November (alt color)
  Item #1 (normal color)
  Item #2 (alt color)
  Item #3 (normal color)
... etc

In other words, it doesn't recognize the TBODY selector for some reason. What did I do wrong?

Thanks.

Upvotes: 0

Views: 601

Answers (2)

PerryW
PerryW

Reputation: 1436

Looking at the OP's original 'What I want'

Solution looks more like

$(document).ready(function () {
  $("tbody").find("tr:even:not(:first)").addClass("alternate-row");
});

Fiddle

Upvotes: 1

nrodic
nrodic

Reputation: 3021

If I understand the problem correctly, this might be what you want:

$("table > tbody").each( function() {
    $("tr:even:not(:first)", this).addClass("alternate-row");
} );

jsfiddle

Problem with your code is selecting all TRs at once.

Upvotes: 4

Related Questions