How to create a Zebra Stripes table effect using jQuery ?
Last Updated :
24 Jan, 2021
Given an HTML document with a table and the task is to create a Zebra Stripes table effect on the table using jQuery.
Approach : To achieve the Zebra Stripes table effect, use the below code snippet:
$(function() {
$("table tr:nth-child(odd)").addClass("zebrastripe");
});
In the above function, zebrastripe is the class name used and odd depicts that odd number of rows will have colored stripes.
To change the even row stripes just use :
$(function() {
$("table tr:nth-child(even)").addClass("zebrastripe");
})
In the below demonstration of the above approach the jQuery-3.5.1.js contains the source code.
Example: Below is the demonstration of the above approach.
HTML
<html>
<head>
<title>jQuery Zebra Stripes Demonstration</title>
<script type="text/javascript" src=
"https://code.jquery.com/jquery-3.5.1.js">
</script>
<script type="text/javascript">
$(function() {
$("table tr:nth-child(odd)")
.addClass("zebrastripe");
});
</script>
<style type="text/css">
body,
td {
font-size: 10pt;
text-align: center;
}
h1 {
color: green;
}
table {
background-color: black;
border: 1px black solid;
border-collapse: collapse;
}
th {
font-size: 15px;
padding: 5px 8px;
border: 1px outset silver;
background-color: rgb(197, 69, 69);
color: white;
}
tr {
border: 1px outset silver;
padding: 5px 8px;
background-color: white;
margin: 1px;
}
tr.zebrastripe {
background-color: green;
}
td {
border: 0.5px outset silver;
border-collapse: collapse;
padding: 5px 8px;
}
.center {
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<h1>
GeeksforGeeks
</h1>
<table class="center">
<tr>
<th>ID</th>
<th>Course</th>
<th>Price</th>
</tr>
<tr>
<td>1</td>
<td>Fork CPP</td>
<td>Free</td>
</tr>
<tr>
<td>2</td>
<td>DSA</td>
<td>2499</td>
</tr>
<tr>
<td>3</td>
<td>Fork Java</td>
<td>Free</td>
</tr>
<tr>
<td>5</td>
<td>Linux</td>
<td>599</td>
</tr>
<tr>
<td>6</td>
<td>Fork Python</td>
<td>Free</td>
</tr>
</table>
</body>
</html>
Output:
Output of the above demonstration