jQuery Add and Remove CSS Classes

In jQuery, you can dynamically add or remove CSS classes to HTML elements, allowing for dynamic styling and interaction. The addClass() and removeClass() methods are the primary tools for achieving this functionality.

Adding a Class

Suppose you have an HTML element like this:

<div id="myDiv">This is a div element</div>

To add a CSS class to this <div> element, using jQuery, you can use the addClass() method:

$("#myDiv").addClass("highlight");

In this example, the "highlight" class will be added to the <div> element, allowing you to apply predefined styling rules.

Removing a Class

Continuing from the previous example, to remove a class from an element, use the removeClass() method:

$("#myDiv").removeClass("highlight");

This will remove the "highlight" class from the <div> element, reverting its styling to its original state.

Toggling a Class

The toggleClass() method provides a convenient way to toggle the presence of a class. If the class is already applied to the element, calling toggleClass() will remove it. If the class is not applied, calling toggleClass() will add it:

$("#myDiv").toggleClass("highlight");

This means you can use the same method to switch a class on and off based on user interactions.

Conclusion

addClass() and removeClass() methods that allow you to dynamically add or remove CSS classes from HTML elements. These methods enable flexible and interactive styling changes, aiding in creating dynamic user experiences without direct manipulation of class attributes in the code. Additionally, the toggleClass() method offers a convenient way to toggle the presence of a class based on user interactions.