HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery CSS Classes

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.


The Four Class Methods

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).

1. addClass() and removeClass()

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");

2. toggleClass()

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");
});

3. hasClass() — Logic Control

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.");
}
Why favor Classes over .css()? Scaling. If you want to change your site's "highlight" color from blue to green, you only have to change one line in your CSS file if you used classes. If you used .css(), you would have to find and replace every line of JavaScript.

Practical Example: Hover Effect

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");
});
Pro Tip: You can chain these methods like any other. For example: $("#target").removeClass("old").addClass("new").slideDown();

Key Points to Remember

  • addClass/removeClass handle one or more space-separated classes.
  • toggleClass is the most efficient way to switch states.
  • hasClass is used for conditional logic (if/else).
  • Always prefer class manipulation over inline .css() for better maintenance.
  • These methods handle the className attribute behind the scenes for you automatically.