jQuery | last() with Examples

The last() function is an inbuilt function in jQuery which is used to find the last element of the specified elements.
Syntax:

$(selector).last()

Here selector is the selected elements.
Parameters: It does not accept any parameter.
Return value: It returns the last element out of the selected elements.

JavaScript code to show the working of this function:

Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
   <head>
      <script src=
      </script>
      <script>
         $(document).ready(function(){
            $("p").last().css("background-color", "lightgreen");
         });
      </script>
   </head>
   <body>
      <h1>Welcome to GeeksforGeeks !!!</h1>
      <p style="padding:5px; border:1 px solid green">
        This is the First.</p>
      <p style="padding:5px; border:1 px solid green">
        This is the Second.</p>
      <p style="padding:5px; border:1 px solid green">
        This is the Third.</p>
      <br>
   </body>
</html>

chevron_right


In this code the background-color of the last “p” element get changed.
Output:

Code #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    <script src=
    </script>
    <script>
        $(document).ready(function() {
            $(".main").last().css("background-color", "lightgreen");
        });
    </script>
</head>
  
<body>
    <h1>Welcome to GeeksforGeeks !!!</h1>
    <div class="main" style="border: 1px solid green;">
        <p>This is the First.</p>
    </div>
    <br>
    <div class="main" style="border: 1px solid green;">
        <p>This is the Second.</p>
    </div>
    <br>
    <div style="border: 1px solid green;">
        <p>This is the Third.</p>
    </div>
    <br>
</body>
  
</html>

chevron_right


In the above example the last elements with class “main” get highlighted.
Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.