jQuery Odd and even Filters

jQuery provides some additional tweaking to filter your choices.

The :even filter allows you to select every even element in a collection of elements. For example, to find every even row of a table, you can write jQuery selector something like :

$('tr:even')

To find odd rows of a table, you can use

$('tr:even')

Before we discuss further, we would like to illustrate with an example to beautify alternate rows of a Table with a give color. highligted the text based upon selection by id attribute


<html>
<head>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function(){
  $("tr:even").css("background-color", "gainsboro");
  $("tr:odd").css("background-color", "ghostwhite");

});
 </script>
<body>

<h1>List of Cars </h1>

<table border=1>
  <tbody>
    <tr>
      <td>Make</td>
      <td>Model</td>
    </tr>
    <tr>
      <td>Toyota</td>
      <td>Corolla</td>
    </tr>
    <tr>
      <td>Honda </td>
      <td>Civic</td>
    </tr>
    <tr>
      <td>Ford </td>
      <td>Focus</td>
    </tr>
  </tbody>
</table>

</body>
</html>



You may like to try this example here.

If you have two tables with two different ids then you can apply the selection to choose the table inwhich you wish to apply the changes. For example if you have two tables

<table id='id1'></table> and <table id='id2'></table>

and if you wish to apply the selection only to the first table, you can use

$(document).ready(function()
{
  $("table#id1 tr:even").css("background-color", "gainsboro");
  $("table#id1 tr:odd").css("background-color", "ghostwhite");
});

We will leave it as an exercise for you to take the previous example, create two tables and apply the changes to that only one table is affected.