-2

I want to color every second row of a table. While every regular table can be colored using this:

$('tr:odd').css( "background-color", "orange" );

In my case there are several rowspan, what makes the task more difficult.

This is my desired output:

desired table

Using this code above doesn't lead to the desired result:

enter image description here

Here is a fiddle.

$('tr:odd').css("background-color", "orange");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td rowspan="2">Col 1</td>
    <td>Col 2</td>
    <td rowspan="2">Col 3</td>
  </tr>
  <tr>
    <td>Col 1</td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td rowspan="2">Col 1</td>
    <td rowspan="2">Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td>Col 1</td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
</table>
CalvT
  • 3,123
  • 6
  • 37
  • 54
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181

1 Answers1

5

Do something like this:

$("table tr").filter(function() { 
  return $(this).children().length == 3;
}).filter(':odd').addClass('alt');

$("tr.alt td[rowspan]").each(function() {
  $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
});
.alt { background-color: orange; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td rowspan="2">Col 1</td>
    <td>Col 2</td>
    <td rowspan="2">Col 3</td>
  </tr>
  <tr>
    <td>Col 1</td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td rowspan="2">Col 1</td>
    <td rowspan="2">Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td>Col 1</td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
</table>
void
  • 36,090
  • 8
  • 62
  • 107