Skip to content
Related Articles

Related Articles

How to add a class to the last paragraph element using jQuery ?
  • Last Updated : 31 Dec, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Before Click the Button:

After Click the Button:

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :