Open In App
Related Articles

jQuery last() Method

Improve Article
Improve
Save Article
Save
Like Article
Like

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:

Example 1:

html




<!DOCTYPE html>
<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>


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

Output:

Example 2:

html




<!DOCTYPE html>
<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>


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

Output:


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 07 Jul, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials