Skip to content
Related Articles

Related Articles

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

Improve Article
Save Article
  • Last Updated : 31 Dec, 2020
Improve Article
Save Article

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:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!