jquery
  1. jquery-addclass

jQuery addClass()

The jQuery addClass() method is used to add one or more CSS classes to an HTML element. It can help you to style your webpage dynamically by changing the appearance of an element based on a user interaction or a specific event.

Syntax

The addClass() method takes one or more parameters, which represent the classes you want to add to the selected element. Here is the syntax:

$(selector).addClass(class1, class2, ...);

Use

The addClass() method is used to modify the CSS classes of an element based on a specific condition. You can use jQuery to add classes dynamically to HTML elements, such as buttons, forms, or menus, based on user interactions or specific events.

For example, you can add a class to a button to change its text color when a user hovers over it, or add a class to a form to change its background color when it is submitted successfully.

Example

Here is an example of using addClass() to modify the class of an HTML element:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery addClass() - Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .blue {
            color: blue;
        }
    </style>
</head>
<body>
    <button id="myButton">Click me</button>

    <script>
        $(document).ready(function(){
            $("#myButton").click(function(){
                $(this).addClass("blue");
            });
        });
    </script>

</body>
</html>
Try Playground

In this example, we use jQuery to add a class blue to the button element with the id myButton whenever the button is clicked. We have defined the blue class in the <style> tag, which sets the color of the text of the button to blue.

Summary

The jQuery addClass() method is a useful tool for modifying the CSS classes of an element based on a specific condition or event. With its easy-to-use syntax and dynamic nature, it can help you to style your webpage in innovative and exciting ways. Try using addClass() today to add some interactivity to your website!

Published on: