jQuery - Get and Set CSS Classes


jQuery Manipulating CSS

jQuery has various ways to change how things look on a webpage using CSS. We'll explore the following methods:

  • addClass() - Adds one or more classes to the selected elements
  • removeClass() - Removes one or more classes from the selected elements
  • toggleClass() - Toggles between adding/removing classes from the selected elements
  • css() - Sets or returns the style attribute

Example Stylesheet

The style rules below will be applied to all the examples on this webpage.

.important {
  font-weight: bold;
  font-size: xx-large;
}

.blue {
  color: blue;
}

jQuery addClass() Method

In this example, you'll see how to assign a class to various elements. You can assign classes to multiple elements as needed.

You can add more than one class using the addClass() method by specifying them together.


jQuery removeClass() Method

Here's an example that demonstrates how to take away a particular class feature from various elements:


jQuery toggleClass() Method

Here's an example that demonstrates how to utilize the jQuery method called toggleClass(). This method allows you to switch between adding and removing classes from the elements you've selected. It's a handy way to change the appearance or behavior of your web page elements dynamically


jQuery css() Method

In the upcoming chapter, we'll talk about how the jQuery method called css() works.