jQuery Add/Remove Classes

addClass() Method

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute.
$("p1").addClass("highlight1"); $("div1").addClass("highlight2");
<style> .highlight1 { background:red; } .highlight2 { background:green; } </style>
<p class="p1">This is a paragraph</p> <div class="div1"> This is a Div</div>

The above code add two classes for p and div elements and changed the backgroung when click the button.

removeClass() Method

The removeClass() enables you to remove a single class, multiple classes, or all classes from each element in the set of matched elements.
$(".p1").removeClass("highlight1"); $(".div1").removeClass("highlight2");

The above code remove two classes for p and div elements and changed the backgroung when click the button.

run this source code Browser View

This is a paragraph



This is a Div


Full Source
<html> <head> <title>Hello World</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#bt1").click(function(){ $("p").addClass("highlight1"); $("div").addClass("highlight2"); }); $("#bt2").click(function(){ $("p").removeClass("highlight1"); $("div").removeClass("highlight2"); }); }); </script> <style> .highlight1 { background:red; } .highlight2 { background:green; } </style> </head> <body> <p>This is a paragraph</p> <div> This is a Div</div> <br> <button id="bt1" >Add Class</button> <button id= "bt2">Remove Class</button> </body> </html>