How to create a table Zebra Stripes effect – JQuery
Written on
November 20, 2008 at 2:59 pm by
mkyong
Here is a simple example to show how to create a table Zebra Stripes effect with JQuery.
<html>
<head>
<title>JQuery Zebra Stripes</title>
</head>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript">
$(function() {
$("table tr:nth-child(even)").addClass("striped");
});
</script>
<style>
body,td {
font-size: 10pt;
}
table {
background-color: black;
border: 1px black solid;
border-collapse: collapse;
}
th {
border: 1px outset silver;
background-color: maroon;
color: white;
}
tr {
background-color: white;
margin: 1px;
}
tr.striped {
background-color: coral;
}
td {
padding: 1px 8px;
}
</style>
</script>
<body>
<table>
<tr>
<th>ID</th>
<th>Fruit</th>
<th>Price</th>
</tr>
<tr>
<td>1</td>
<td>Apple</td>
<td>0.60</td>
</tr>
<tr>
<td>2</td>
<td>Orange</td>
<td>0.50</td>
</tr>
<tr>
<td>3</td>
<td>Banana</td>
<td>0.10</td>
</tr>
<tr>
<td>4</td>
<td>strawberry</td>
<td>0.05</td>
</tr>
<tr>
<td>5</td>
<td>carrot</td>
<td>0.10</td>
</tr>
</table>
</body>
</html>See, how powerful JQuery is. The zebra stripes effect was achieved with one line effort.
$(function() {
$("table tr:nth-child(even)").addClass("striped");
});Explanation
1) $() = JQuery function
2) table = table html tag
3) tr = table tr html tag
4) nth-child(even)”).addClass(“striped”) = every even row add “striped” CSS class dynamicly.
JQuery help we do everything. We can dynamic load a CSS class into a tr row now~


