As a web developer, you are often required to add, remove, and toggle CSS classes based on user interactions with elements on the web page. If you had already used jQuery in the past, you'd be probably familiar with the addClass()
, removeClass()
, and toggleClass()
methods.
In modern JavaScript, it makes no sense to load the complete jQuery library to do some simple DOM manipulations. In this article, you'll learn how to add, remove, and toggle CSS classes in JavaScript without jQuery.
Set CSS classes using the className
property
The simplest way to get and set CSS classes in JavaScript is using the className
property. It refers to the value of the HTML element's class
attribute.
Let us say we have the following HTML element:
<div class="pizza">🍕</div>
The following example shows how to add a new CSS class or replace all existing CSS classes of the above <div>
element:
const pizza = document.querySelector('.pizza')
// print existing classes
console.log(pizza.className) // pizza
// add new `.spicy` class
pizza.className += 'spicy'
// replace all existing classes
pizza.className = 'hot spicy pizza'
Since class
is a reserved word in JavaScript, the name className
is used for this property. This property is supported by all modern and old browsers, including Internet Explorer.
Set CSS classes using the classList
property
There is even a better way to manipulate CSS classes in JavaScript, thanks to the classList
property. It is a read-only property that returns a live DOMTokenList collection of all the classes applied to the element.
The classList
property works in all modern browsers and IE10 and above.
You can use the classList
property to easily add, remove, and toggle CSS classes from an element in vanilla JavaScript.
Say we have an element like the below:
<div class="hot spicy pizza">
🍕
</div>
Let us grab a reference to the above <div>
element and print the existing classes on the console:
// grab element reference
const pizza = document.querySelector('.pizza')
// get all existing classes
console.log(pizza.classList)
// ["hot", "spicy", "pizza", value: "hot spicy pizza"]
// get first class name
console.log(pizza.classList[0]) // hot
// get total number of classes
console.log(pizza.classList.length) // 3
Let us now look at the popular methods of the DOMTokenList
collection, returned by the classList
property. We'll use these methods to manage and update CSS classes for an HTML element.
item()
Method
The item()
method returns the class in the collection by its index, or undefined
if the index is greater than or equal to the list's length
property:
console.log(pizza.classList.item(1)) // spicy
add()
Method
The add()
method adds one or more classes to the HTML element:
pizza.classList.add('sauce', 'cheese', 'tomato')
Now, the element looks like the below:
<div class="hot spicy pizza sauce cheese tomato">
🍕
</div>
If you try to add a class that already exists, the add()
method will ignore it. To see how it works, let us add more cheese
to the pizza:
pizza.classList.add('cheese')
Here is the element now:
<div class="hot spicy pizza cheese tomato">
🍕
</div>
contains()
Method
The contains()
method returns true
if the element contains the given class, otherwise false
:
console.log(pizza.classList.contains('cheese')) // true
console.log(pizza.classList.contains('yogurt')) // false
remove()
Method
The remove()
method is used to remove one or more classes from the element:
pizza.classList.remove('sauce', 'potato')
If you try to remove a class that doesn't exist, as we did in the above example, there won't be any error. JavaScript will completely ignore it.
toggle()
Method
The toggle()
method removes the class if it already exists. Otherwise, it adds to the collection.
Without this method, you have to manually check if the class exists using contain()
before toggling it on or off:
// manual toggle
if (pizza.classList.contains('olive')) {
pizza.classList.remove('olive')
} else {
pizza.classList.add('olive')
}
With the toggle()
method, you pass the name of the class which you want to toggle:
pizza.classList.toggle('olive')
The toggle()
method returns true
if the class was added and false
if it was removed:
const status = pizza.classList.toggle('olive')
console.log(status) // true --> class was added
You can also pass a second boolean parameter to the toggle()
method to indicate whether to add the class or remove it. This will turn toggle()
into one way-only operation.
If the second argument evaluates to false
, then the class will only be removed but not added. If it evaluates to true
, then the class will only be added but not removed.
Here is an example:
const status = pizza.classList.toggle('hot', false)
console.log(status) // false --> class was removed
replace()
Method
The replace()
method can be used to replace a CSS class with another class:
pizza.classList.replace('spicy', 'olive')
This method returns true
if the target class is successfully replaced with the new class. Otherwise, false
.
The
replace()
method is not supported by Internet Explorer. You can useremove()
along withadd()
to replace a CSS class in older browsers.
forEach()
Method
The DOMTokenList
collection also supports the forEach() method to iterate over all the classes:
// iterate over all classes
pizza.classList.forEach((item, index) => {
console.log(item)
})
Conclusion
That's all! In this article, we looked at two properties (className
& classList
) to manipulate CSS classes in JavaScript.
The className
property presents the class
attribute of the element and is supported by all browsers, including Internet Explorer. It can be used to add a new class or replace an existing class.
On the other hand, the classList
property returns a live DOMTokenList
collection of all the classes applied to a DOM element. It can easily add, remove, toggle, and iterate through all CSS classes.
Read Next: Hide and show DOM elements using a CSS class in JavaScript
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.