Open In App

How to add a class on click of anchor tag using jQuery ?

In this article, we will see how to add a class on click of an anchor tag using jQuery. To add a class on click of the anchor tag, we use the addClass() method. The addClass() method is used to add more properties to each selected element. It can also be used to change the property of the selected element. We can also use toggleClass for adding and removing CSS.

Syntax:



$(selector).addClass("active");

In the below example, we are creating an anchor class element and a button, when the user clicks on the button, the addClass() method is called and this method adds a class named “active”. 

Example 1: In this example, we can see the use of addClass.






<!DOCTYPE html>
<html>
<head>
    <title>
        How to add a class on click
        of anchor tag using jQuery?
    </title>
    </script>
    <style>
        .active {
            font-size: 32px;
            color: green;
            font-weight: bold;
            text-decoration: none;
        }
    </style>
    <script>
        $(document).ready(function () {
            $("#btn").on('click', function () {
                $("a").addClass("active");
            });
        });
    </script>
</head>
<body>
    <center>
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
        <h3>
            How to add a class on click
            of anchor tag using jQuery?
        </h3>
        <input type="button" id="btn" value="Add Class" style="padding: 5px 10px;">
        <br><br>
        <a class="" href="https://www.geeksforgeeks.org/">
            GeeksforGeeks
        </a>
    </center>
</body>
</html>

Output:

Example 2: In this example, we will use toggleClass.




<!DOCTYPE html>
<html>
<head>
    <title>
        How to add a class on click
        of anchor tag using jQuery?
    </title>
    </script>
    <style>
        .active {
            font-size: 32px;
            color: green;
            font-weight: bold;
            text-decoration: none;
        }
      </style>
    <script>
         $(document).ready(function () {
                $("#btn").click(function (e) {
                    e.preventDefault();
                    $(this).toggleClass("active");
                });
            });
    </script>
</head>
<body>
    <center>
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
        <h3>
            How to add a class and remove a class on click
            of anchor tag using jQuery?
        </h3>
        <input type="button" id="btn" value="GeeksforGeeks" style="padding: 5px 10px;">
    </center>
</body>
</html>

Output:

 


Article Tags :