Odd & Even Selectors in jQuery

jqueryWhenever you select an element by Tag Name, it will return collection of elements which have the same Tag Name.  That collection always starts from 0.  We can manipulate those elements by their odd and even position in collection using Odd and Even selectors in jQuery.  We are going to use Tag Name and ID selectors along with it.

In the below given example, we have 2 tables.  One has the ID of table1 and another ID of table2.

With Tag Name Selector:  It will select all TR elements in the table and change the background color depending upon their odd and even position in collection.  The syntax for Odd selector is $(‘TagName:Odd’) and for Even selector is $(‘TagName:Even’).

<html>
<head>
<title>jQuery Tutorial </title>
 
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
 
 $(document).ready(function () {
    
    $('tr:odd').css("background-color", "red");
    $('tr:even').css("background-color", "yellow");
 });
 
</script>
</head>
 
<body>
<table id="table1"  border="1">
<tr>
<th>Male</th>
</tr>
<tr>
<td>Robert</td>
</tr>
<tr>
<td>Peter</td>
</tr>
<tr>
<td>John</td>
</tr>
<tr>
<td>Sam</td>
</tr>
<tr>
<td>Mark</td>
</tr>
</table>
<br />
<table id="table2"  border="1">
<tr>
<th>Female</th>
</tr>
<tr>
<td>Susan</td>
</tr>
<tr>
<td>Jenny</td>
</tr>
<tr>
<td>Maria</td>
</tr>
<tr>
<td>Katrina</td>
</tr>
<tr>
<td>Lilly</td>
</tr>
</table>
 
</body>
</html>

With ID Selector:  It will select all TR elements in the table of ID table1 and change the background color depending upon their odd and even position in collection.  There will be no change in another table.  The syntax for Odd selector is $(‘#ElementID TagName:Odd’) and for Even selector is $(‘#ElementID TagName:Even’).

<html>
<head>
<title>jQuery Tutorial </title>
 
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
 
 $(document).ready(function () {
    
    $('#table1 tr:odd').css("background-color", "red");
    $('#table1 tr:even').css("background-color", "yellow");
 });
 
</script>
</head>
 
<body>
<table id="table1"  border="1">
<tr>
<th>Male</th>
</tr>
<tr>
<td>Robert</td>
</tr>
<tr>
<td>Peter</td>
</tr>
<tr>
<td>John</td>
</tr>
<tr>
<td>Sam</td>
</tr>
<tr>
<td>Mark</td>
</tr>
</table>
<br />
<table id="table2"  border="1">
<tr>
<th>Female</th>
</tr>
<tr>
<td>Susan</td>
</tr>
<tr>
<td>Jenny</td>
</tr>
<tr>
<td>Maria</td>
</tr>
<tr>
<td>Katrina</td>
</tr>
<tr>
<td>Lilly</td>
</tr>
</table>
 
</body>
</html>