How to use the prop() method In JQuery

The prop() method of jQuery can also be used to add a new class to the selected element in the same way as we used the attr() method by passing a callback function to set the new value of the passed property.

Syntax:

$('element_selector').prop('class', (i, prevClass)=>{});

Example: This example implements the prop() method to add the class to a element.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <style>
        .GFG1 { 
            font-weight: bold;
        }
 
        .GFG2 {
            font-size: 24px;
            color: green;
        }
    </style>
 
    <!-- Import jQuery cdn library -->
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
 
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").prop("class", (i, prevClass)=>{
                    return prevClass + " GFG2";
                });
            });
        });
    </script>
</head>
 
<body style="text-align: center;">
    <h1 style="color: green;">
        w3wiki
    </h1>
 
    <h3>
        How to add a new class to an element that
        <br>already has a class using jQuery?
    </h3>
 
    <p class="GFG1">
        w3wiki, A computer science portal
    </p>
 
    <button>Click to Add class</button>
</body>
 
</html>


Output:



How to add a new class to an element that already has a class using jQuery ?

In this article, we will learn to add a new class to an element that already has a class using jQuery. There are different methods of achieving this task using the built-in methods available in jQuery. The approaches we can use to add a class to an element using jQuery are listed below:

Table of Content

  • Using the addClass() method
  • Using the attr() method
  • Using the prop() method

Similar Reads

Using the addClass() method

The addClass() method of jQuery can be used to add a class to an element. We can use the addClass() method by passing the name of the class that has to be added as a parameter in the form of a string and it will add that class to the selected element....

Using the attr() method

...

Using the prop() method

We can also use the attr() method and add the class attribute to the selected element. But, we have to set the value of this attribute using a callback function which allow us to access the previous value of the same attribute and add a new value to the previous value....