CSS vs jQuery How to create dynamic table style (zebra) without other plugins?
I need to create a table like a zebra, style even table rows, I used css :nth-of-type(even)
. But, for example, when I need to hide some styled table elements, it gets lost. What's the easiest way to create a dynamic zebra style 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?
Current
Output : Expected Output:
source to share
When you hide an element, it's still there (just hidden), which is why you have this problem. I suggest you create a simple script versus css selector :nth-of-type(even)
. First, there are two classes:
.table_odd { color: yellow; }
.table_even {color: white; }
Now the 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 the use is simple. The document call is ready and when you hide the element:
refrestTableColoring( $('table') );
source to share
instead of hide () , you can use remove () for this . Write like this:
$('input[type="submit"]').click(function(){
$(".hidden").remove();
});
Check out http://jsfiddle.net/fhbgM/
source to share