Open In App

How to add a class to the last paragraph element using jQuery ?

Last Updated : 31 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn to add a class to the last paragraph element using jQuery. To add a class to the last paragraph element, we use last() and addClass() methods. The jQuery last() function is an inbuilt function that is used to find the last element of the specified elements.

Syntax:

$(selector).last()

The addClass() method is used to add more classes and their respective properties to each selected element. It can also be used to change the property of the selected element. Here, the class name can be used directly with the element which is going to be selected.

Syntax:

$(selector).addClass(className);

Example:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <style>
        .GFG {
            color: green;
            font-size: 24px;
            font-weight: bold;
        }
    </style>
  
    <!-- Import jQuery cdn library -->
    <script src=
    </script>
  
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").last().addClass("GFG");
            });
        });
    </script>
</head>
  
<body style="text-align: center;">
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
  
    <h3>
        How to add a class to the last
        paragraph element using jQuery?
    </h3>
   
    <p>GeeksforGeeks computer science portal</p>
  
    <button>Click Here!</button>
</body>
  
</html>


Output:

Before Click the Button:

After Click the Button:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads