JQuery Select First or Last Element

From CoderLearner
Jump to: navigation, search

Search for first or last element

Sometime it is beneficial to find the last or the first element.

Example 1

Assign css color to blue for the first p element.

// <div>My First</div> is blue color
$('div:first').css('color','blue');

<div>My First</div>
<p>My second</p>
<div>Second Div</div>
<div>Third Div</div>

Example 2

Assign css color to blue for the last element.


// <p>Fourth</p> 
$('p:last').css('color','blue');

<p>First</p>
<p>Second</p>
<p>Third</p>
<p>Fourth</p>

Example 3

<!DOCTYPE html>
<html>
   <head>
      <title>odd even</title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <script 
         type="text/javascript" 
         src="/lib/jquery-1.7.2.min.js">				 
      </script>
      <style>
         .gg1
         {
            background-color: #6699CC;
         }

         .gg2 
         {
            background-color: #999900;
         }
      </style>
      <script>
         $(document).ready(function(){
            $('tr:first').addClass('gg1');
            $('tr:last').addClass('gg2');
         });
      </script>

   <body>
      <table>
         <tr>
            <th>Gender</th>
            <th>Population</th>
            <th>Unknown</th>
            <th>Study</th>
         </tr>
         <tr>
            <td>Male-Unknown</td>
            <td>400</td>
            <td>30%</td>
            <td>70%</td>
         </tr>
         <tr>
            <td>Male-India</td>
            <td>800</td>
            <td>10%</td>
            <td>90%</td>
         </tr>
         <tr>
            <td>Female-Vietnamese</td>
            <td>800</td>
            <td>20%</td>
            <td>80%</td>
         </tr>
         <tr>
            <td>Male-White</td>
            <td>800</td>
            <td>20%</td>
            <td>80%</td>
         </tr>
      </table>
   </body>
</html>

Try It

<seo metagenerator="jquery tutorial" title="Jquery/Ajax" metakeywords="jquery greater,jquery gt, jquery lt, less then, odd jquery,jquery find element, even jquery,jquery event, jquery mouse click, jquery double click, jquery hover, jquery string, jquery array, jquery button, jquery attriubtes" metadescription="jquery button, jquery attriubte, jquery example, jquery tutorial, jquery sample"/>