jQuery CSS

jQuery Get and Set CSS Classes

Manipulating CSS classes is one of the most common uses for jQuery.

Instead of changing inline CSS styles individually, it is much cleaner to toggle predefined classes.


jQuery CSS Class Methods

jQuery provides three highly optimized methods for class manipulation:


The addClass() Method

The addClass() method attaches a class to an element without overwriting its existing classes.

You can also pass multiple classes at the same time by separating them with a space.

Add Class Example:

$("button").click(function(){
  $("h1, h2, p").addClass("blue");
  $("div").addClass("important blue");
});

The removeClass() Method

If an element has a class you no longer want, removeClass() takes care of it.

This is perfectly suited for removing "active" states from navigation menus.

Remove Class Example:

$("button").click(function(){
  $("h1, h2, p").removeClass("blue");
});

The toggleClass() Method

The toggleClass() method is incredibly powerful for interactive UI elements.

It checks if a class exists. If it exists, it removes it. If it doesn't exist, it adds it.

Toggle Class Example:

$("button").click(function(){
  $("h1, h2, p").toggleClass("blue");
});

Exercise 1 of 1

?

Which method is best for creating a button that switches a dark-mode theme on and off?