Manipulating CSS classes is the professional way to change the design of your website. Instead of injecting styles directly into your HTML, you can define classes in your CSS file and use jQuery to "flip the switch." This keeps your code clean, organized, and easy to maintain.
jQuery provides four fundamental methods for class manipulation:
| Method | Description |
|---|---|
addClass() |
Adds one or more classes to the selected elements. |
removeClass() |
Removes one or more classes from the selected elements. |
toggleClass() |
Toggles between adding and removing classes. |
hasClass() |
Checks if a class exists on an element (returns true/false). |
You can add or remove a single class or multiple classes at once (separated by spaces).
// Adding classes
$("h1").addClass("title-theme shadow");
// Removing classes
$("p").removeClass("blue-text error-box");
The toggleClass() method is a huge time-saver. It automatically adds the
class if it's missing, and removes it if it's already there. This is perfect for buttons
that enable/disable features.
// Perfect for Dark Mode toggles
$("#themeBtn").click(function() {
$("body").toggleClass("dark-mode");
});
Sometimes you need to know if an element *already* has a class before performing an
action. The hasClass() method returns a boolean value.
if ($("#myBox").hasClass("active")) {
$("#status").text("Element is currently active.");
}
.css(), you would have to find and replace every line of JavaScript.
Let's create an effect where a box grows and changes color when hovered, without using .css().
// In CSS:
// .active-box { border: 2px solid blue; background: #eee; transform: scale(1.1); }
// In jQuery:
$(".demo-box").hover(function() {
$(this).addClass("active-box shadow");
}, function() {
$(this).removeClass("active-box shadow");
});
$("#target").removeClass("old").addClass("new").slideDown();
.css() for better
maintenance.