3

I need to style the table as a zebra, styling even rows of tables, I used the css :nth-of-type(even). But for example when I need to hide some of the stylized elements of the table is lost. What's the easiest way to create a dynamic styling as a zebra for a table?

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <style type="text/css">
    table tr:nth-of-type(even){background: yellow;}
  </style>
  <script type="text/javascript">
    function hideRow(){
      $(".hidden").hide();
    }
  </script>
</head>
<body>
<center>
 <table cellspacing="0" border="1">
     <tbody>
    <tr class="table-row">
      <td>row1</td>
    </tr>
    <tr class="table-row">
      <td>row2</td>
    </tr>
    <tr class="table-row hidden">
      <td>row3</td>
    </tr>
    <tr class="table-row">
      <td>row4</td>
    </tr>
    <tr class="table-row">
      <td>row5</td>
    </tr>
    </tbody>
 </table>
 <input type="submit" onclick=" hideRow()" value="submit"/> 
 </center>
</body>
</html>

How can I dynamically change the style of the table?

Сurrent result:
enter image description here enter image description here
Expected result:
enter image description here enter image description here

Community
  • 1
  • 1
Igor Slipko
  • 105
  • 1
  • 1
  • 5
  • possible duplicate of [Zebra striping a table with hidden rows using CSS3?](http://stackoverflow.com/questions/3773890/zebra-striping-a-table-with-hidden-rows-using-css3) – epascarello Jan 22 '13 at 13:26

3 Answers3

1

When you hiding elemment, its still there (just hidden), so thats why you have this problem. Ill suggest you to create simple script against css :nth-of-type(even) selectors. First, two clases:

.table_odd { color: yellow; } 
.table_even {color: white; }

Now crete function:

function refrestTableColoring( $tableSelector ) {
    $tableSelector.find('tr:odd:not(.hidden)').removeClass('table_even').addClass('table_odd');
    $tableSelector.find('tr:even:not(.hidden)').removeClass('table_odd').addClass('table_even'); 
}

And then usage is simple. Call on document ready and when you're hiding element:

refrestTableColoring( $('table') );
Kasyx
  • 3,170
  • 21
  • 32
  • 1
    Thanks, this decision was very helpful, just a little tweak to the selector: 'tr:not(.hidden):odd' and 'tr:not(.hidden):even' – Igor Slipko Jan 22 '13 at 14:09
0
 table tr[@display=block]:nth-of-type(even){background: yellow;}

will this work?

Disclaimer:untested

Abhijit Mazumder
  • 8,641
  • 7
  • 36
  • 44
0

instead of hide() you can use remove() for this. Write like this:

$('input[type="submit"]').click(function(){
    $(".hidden").remove();
});

Check this http://jsfiddle.net/fhbgM/

sandeep
  • 91,313
  • 23
  • 137
  • 155