How To Change Class In Jquery

When working with HTML and CSS, classes are used to apply styling to a group of elements. If you want to change the look and feel of some elements on your page without refreshing the entire page, you can use jQuery to modify the class attribute of those elements.

In this blog post, we will discuss two methods in jQuery to change the class of the selected elements:

  • addClass()
  • removeClass()

Prerequisite

Before we dive into the methods, make sure you have included the jQuery library in your HTML file. You can either download the jQuery library and include it locally or use the CDN like shown below:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

The addClass() Method

The addClass() method in jQuery is used to add one or more classes to the selected elements. The syntax for the addClass() method is as follows:

$(selector).addClass(classname,function(index,currentclass))

Here, classname is the name of the class you want to add, and the optional function(index, currentclass) is a function that returns the class name(s) to add.

Let’s see an example:

<button id="btn">Click to change class</button>
<div id="demo" class="old-class">This is a demo div.</div>

<script>
  $("#btn").click(function(){
    $("#demo").addClass("new-class");
  });
</script>

In this example, when the button with the ID btn is clicked, the new-class will be added to the div with the ID demo.

The removeClass() Method

The removeClass() method in jQuery is used to remove one or more classes from the selected elements. The syntax for the removeClass() method is as follows:

$(selector).removeClass(classname,function(index,currentclass))

Here, classname is the name of the class you want to remove, and the optional function(index, currentclass) is a function that returns the class name(s) to remove.

Let’s see an example:

<button id="btn">Click to change class</button>
<div id="demo" class="old-class">This is a demo div.</div>

<script>
  $("#btn").click(function(){
    $("#demo").removeClass("old-class");
  });
</script>

In this example, when the button with the ID btn is clicked, the old-class will be removed from the div with the ID demo.

Conclusion

Changing the class of an element in jQuery is quite simple with the help of the addClass() and removeClass() methods. Make sure to include the jQuery library in your project and start applying these methods to modify the classes of your elements to create dynamic and interactive web pages.