In jQuery, it is quite easy to manipulate the style of elements. jQuery has several methods to manipulate CSS classes assigned to HTML elements. Let us see how to add or remove css classes using jQuery.

jQuery addclass() Method

The jQuery addclass() method adds one or more classes to the selected elements. While adding classes, you may select multiple elements.

Example for addclass()
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        $("h1").addClass("page-header");
        $("p.hint").addClass("highlight");
    });
});
</script>

In this example code, we are adding the class .page-header to the <h1> and adding the class .highlight to the <p> elements with class .hint.

And also, you can mention multiple classes within the addclass() method at a time. Just specify the space seperated list of classes within the addclass() method.

Adding Multiple Classes
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        $("h1").addClass("page-header highlight");
    });
});
</script>

Removeclass() with JQuery

Likewise, we can remove the classes from the elements using the removeclass() method in jQuery. Using this, we can remove a single class or multiple classes or even all classes at once from the selected elements.

Example code for removeclass()
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        $("h1").removeClass("page-header");
        $("p").removeClass("hint highlight");
    });
});
</script>

The above code will shows you that will remove the class .page-header from the <h1> and .hint & .highlight from the <p> elements.

If you mention removeclass() without an argument, then it will remove all the classes from the selected elements, as shows below.

Using removeclass() without Argument
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        $("h1").removeClass();
        $("p").removeClass();
    });
});
</script>

jQuery Toggleclass()

It will add or remove one or more classes from the selected elements in a way if the choosed element already has the class, then it is removed. If the selected element doesn’t has the class, then it is added as toggle class.

Toggleclass() Example
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("p").click(function(){
        $(this).toggleClass("highlight");
    });
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *