jQuery provides a set of methods for dynamically adding, removing, toggling, and checking CSS classes on HTML element
Methods for CSS Class Manipulation
.addClass()
- Adds one or more classes to the selected elements.
Syntax:
.removeClass()
- Removes one or more classes from the selected elements.
Syntax:
$(selector).removeClass(className);
Example:
$("#myDiv").removeClass("highlight");
.toggleClass()
- Adds the class if it doesn’t exist; removes it if it does. This is useful for toggling between states.
Syntax:
$(selector).toggleClass(className);
Example:
$("#myDiv").toggleClass("highlight");
.hasClass()
- Checks whether an element has a specific class.
Syntax:
$(selector).hasClass(className);
Example:
if ($("#myDiv").hasClass("highlight")) { alert("The element has the 'highlight' class."); }
Examples
Adding and Removing Classes
<div id="myDiv">Hello World</div> <button id="addClass">Add Class</button> <button id="removeClass">Remove Class</button>
$("#addClass").click(function() { $("#myDiv").addClass("highlight"); }); $("#removeClass").click(function() { $("#myDiv").removeClass("highlight"); });
Toggling Classes
<div id="myDiv">Toggle Me</div> <button id="toggleClass">Toggle Class</button>
$("#toggleClass").click(function() { $("#myDiv").toggleClass("highlight"); });
Checking for a Class
<div id="myDiv" class="highlight">Check Me</div> <button id="checkClass">Check Class</button>
$("#checkClass").click(function() { if ($("#myDiv").hasClass("highlight")) { alert("The element has the 'highlight' class."); } else { alert("The element does not have the 'highlight' class."); } });
Applying Multiple Classes
You can add or remove multiple classes at once by separating them with spaces.
$("#myDiv").addClass("class1 class2"); $("#myDiv").removeClass("class1 class2");
Using a Function in Class Methods
You can pass a function to
.addClass()
,.removeClass()
, or.toggleClass()
to dynamically decide the class name.$("#myDiv").addClass(function(index, currentClass) { if (currentClass === "highlight") { return "highlight2"; } else { return "highlight"; } });
Practical Use Case: Active Menu Item
<ul> <li class="menu">Home</li> <li class="menu">About</li> <li class="menu">Contact</li> </ul>
$(".menu").click(function() { $(".menu").removeClass("active"); $(this).addClass("active"); });
When a menu item is clicked, the
active
class is applied to the clicked item, and removed from the others.Best Practices
- Avoid Inline Styling: Use CSS classes for styling and manipulate them dynamically with jQuery, rather than directly altering styles.
- Optimize Performance: For large DOM manipulations, batch your operations to avoid unnecessary reflows or repaints.
- Event Delegation: If adding classes to dynamically created elements, use event delegation with
.on()
.
Summary
jQuery’s class manipulation methods—
.addClass()
,.removeClass()
,.toggleClass()
, and.hasClass()
—offer powerful tools for dynamically modifying the appearance and behavior of elements.