jQuery CSS Manipulation
jQuery provides powerful and easy-to-use methods to work with CSS. Whether you're adding styles, removing them, or toggling between classes, jQuery makes it simple. Below are some commonly used methods for CSS manipulation:
- addClass() – Adds one or more CSS classes to selected elements.
- removeClass() – Removes one or more CSS classes from selected elements.
- toggleClass() – Adds a class if it's missing, or removes it if it's already present.
- css() – Gets or sets the value of a specific CSS property.
Example CSS
The examples below will use the following stylesheet:
.important {
font-weight: bold;
font-size: xx-large;
}
.blue {
color: blue;
}
These styles help visually demonstrate how jQuery methods apply different effects to elements by manipulating their classes and styles dynamically.
jQuery addClass() Method
The addClass() method is used to add one or more CSS classes to selected elements. You can target multiple elements at once and apply styles dynamically.
Example
In the example below, when a button is clicked:
- All <h1>, <h2>, and <p> elements receive the class blue.
- All <div> elements are given the class important.
$("button").click(function(){
$("h1, h2, p").addClass("blue");
$("div").addClass("important");
});
This approach allows you to apply consistent styling across multiple elements with just a single jQuery method call.
You can also apply multiple CSS classes at once using the addClass() method. Simply separate the class names with a space inside the string.
Example
In the following code, when the button is clicked, the element with the ID div1 is given both the important and blue classes:
$("button").click(function(){
$("#div1").addClass("important blue");
});
This makes it easy to combine multiple styles in a single method call for more flexible design control.
jQuery removeClass() Method
The removeClass() method is used to remove one or more CSS classes from the selected elements. It's useful when you want to dynamically reset or change styles.
Example
In this example, clicking the button will remove the blue class from all <h1>, <h2>, and <p> elements:
$("button").click(function(){
$("h1, h2, p").removeClass("blue");
});
This allows you to cleanly revert or update styling on the fly.
jQuery toggleClass() Method
The toggleClass() method is a convenient way to add or remove a class from selected elements. If the class is present, it will be removed; if it's not, it will be added. This is especially useful for creating toggle effects with styling.
Example
In the example below, clicking the button will toggle the blue class on all <h1>, <h2>, and <p> elements:
$("button").click(function(){
$("h1, h2, p").toggleClass("blue");
});
This allows you to easily switch styles on and off with a single line of code.