// It overwrites existing classes var h2 = document.querySelector("h2"); h2.className = "test"; // Add new class to existing classes // Note space before new class name h2.className = " test";
// Add new class to existing classes var p = document.querySelector("p"); p.classList.add("test");
In this article, we will see how to add or remove the CSS classes to an element using jQuery. To add the CSS classes to an element we use addClass() method, and to remove the CSS classes we use removeClass() method.
Example: In the this example, we first create an image element and two buttons, the first button for adding CSS classes and the second button for removing CSS classes. When users click on the first button, the addClass() method is called and the class is added to the image element. When the user clicks on the second button, the removeClass() method is called and the class is removed from the image element.
Let’s dig in!
Let’s imagine you have some CSS that affects the color of some text, like this.
And you’ve got some HTML like this.
You want to add the
0 class from an element that has it.
Let’s look at a few techniques that we can combine to do just that.
Getting all of the elements
To get all of the elements we want to modify, we can use the
1 method. You pass in a CSS selector string (any valid CSS selector, including complex ones, will work), and it returns a
2 of matching elements.
Here’s a demo.
Adding and removing classes
You can add and remove classes from an element using the
It provides a handful of methods you can use to add, remove, toggle, and check for classes on an element. We can use the
4 method to add a class, and the
5 method to remove a class. Do not include the leading dot (
6) when passing in the class name.
This method only works on a single element, not a collection of them.
Here’s another demo.
You can also add or remove multiple classes by passing them in as a comma-separate list.
Looping through each element
To add and remove classes from multiple elements, we need to loop through each one in the
2 we get back from the
1 method and use the
3 API with it.
There are many ways to do that, but the two easiest are with the
0 method and the
Here’s a demo of the
And here’s how you’d do it with the
And here’s a demo of the
I generally prefer the
1 loop as I think it’s simpler to write.
0 method can also be called directly on the
2 returned from the
1 method, without saving it to a variable. That might be useful on occasion.
Add A Class To A Body Element Using classList.add().
Add A Class To A Div Element..
Add A Class To A Div Element Using setAttribute().
Add Multiple Classes To An Element..
Add A Class To Multiple List Type Elements..
Add A Class To An Element On Click..
To add the CSS classes to an element we use addClass() method, and to remove the CSS classes we use removeClass() method.
You can use removeAttribute class. For example element. removeAttribute("class"); Then you'll get what you want.