Saturday, July 5, 2014

Change row background color alternatively in HTML table using jQuery or CSS



To Change row background c0lor alternatively in jQuery:
<script>
$(document).ready(function()
{
  $("tr:even").css("background-color", "lightblue");
});
</script>

In CSS
<style type="text/css">
 tr:nth-child(2n) { background-color: #FFEBCD; }
 </style>
There is a small difference between jQuery and CSS.  When counting tr row number, jQuery includes th. Full code example:
<!DOCTYPE html>
<html>
<head>
<script
src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript">
</script>
<script>
$(document).ready(function()
{
  $("tr:even").css("background-color", "lightblue");
});
</script>
<style>
/*tr:nth-child(2n) { background-color: lightblue; }*/
table,th,td
{
border:1px solid black;
border-collapse:collapse;
}
th,td{padding:5px;}
h1 {text-align:center}
</style>
</head>
<body>
<h1>Change row background color alternatively in CSS or jQuery</h1>
<table style="width:100%">
<tr>
  <th>Firstname</th><th>Lastname</th><th>Scores</th>
</tr>
<tr>
  <td>John</td><td>Smith</td><td>100</td>
</tr>
<tr>
  <td>Eve</td><td>Jackson</td><td>94</td>
</tr>
<tr>
  <td>Terry</td><td>Doe</td><td>80</td>
</tr>
<tr>
  <td>Golden</td><td>Wu</td><td>88</td>
</tr>
</table>
</body>
</html>

Video: Change row background color alternatively  in HTML table using jQuery or CSS

No comments:

Post a Comment