Improving CSS with jQuery

CSS selectors allow us to select many element types based on relationships and the pseudo class selectors allow the selection of sub-elements but to date, there is no way to select odd or even members of a group (CSS has no :even pseudo class selector). Fortunately, jQuery does! That means jQuery can be used to suplement the selectors that CSS provides natively. Have a look at this excellent article by Chris Coyier for more information.

In the example below, we've used the jQuery :even selector to style all the even table rows without the need for a class on those rows.

Top 10 counties by population

Rank County Region Population Density
1 Greater London London 7,813,600 4,979
2 West Midlands West Midlands 2,655,200 2,945
3 Greater Manchester North West 2,629,500 2,061
4 West Yorkshire Yorkshire and the Humber 2,249,500 1,109
5 Kent South East 1,427,500 382
6 Essex East 1,412,900 385
7 Merseyside North West 1,353,400 2,099
8 South Yorkshire Yorkshire and the Humber 1,328,300 856
9 Hampshire South East 1,296,900 344
10 Lancashire North West 1,169,300 380

Here's the script that does the work:

<!-- load jQuery from Google CDN -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/
jquery.min.js"></script> <script> $(document).ready(function(){ $("#counties tbody tr:even").css("background-color","#d3e6ff"); }); </script>

Here is part of the markup for the table:

<table id="counties">
   <thead>
      <tr>
         <th>Rank</th>…
…
   <tbody>
      <tr>
         <td>1</td>
         <td>Greater London</td>…

The table has an id="counties" which is used to identify this particular table but other than that there are no ids or classes in the table.

No additional CSS is required because the styling for the even rows is set using the jQuery .css method.