jQuery First and Last Filters

The :first and :last select the first or the last element in a group. As and example, if you wanted to select the first paragraph on a page, you can use:

$('p:first');

And to select the last paragraph on a page, you can use:

$('p:last');



Aa a practical example you may like to highlight the first row of a Table with a different background color.


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

});
 </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.

We have so far been learning how to "select" a particular group of things in a webpage. We have not been focussing on the kind of "actions" that we could perform of these selection. This is deliberate, in order to learn one thing at a time. Once you have mastered how to "select" something we will also learn what kind of actions we can do on the selection. We have used simple css background color change as one way of showing action performed on the selection. But we will see more actions soon. Keep reading.