How to Add Toggle & Remove Class in JavaScript
When working with JavaScript for front-end web development, more often than not you will need to add and remove classes from HTML elements. Traditionally the easiest way to achieve this while maintaining clean, readable code was to implement the jQuery library which provides addClass(), removeClass(), and toggleClass() for working with HTML class attributes. However, there is no need to do this for common DOM manipulations in modern versions of JavaScript.
Set HTML Classes using className
The most straightforward way to get and manipulate HTML classes in JavaScript is with the className
method. It can be used to get all existing, add new and replace all existing class names on an element.
Before we can use cassName
we need to create a constant containing the element. To get the element we will use document.querySelector.
<div class="foo"></div>
const element = document.querySelector('.foo');
To get all existing class names use:
element.className
foo
To add a new class we can concatenate it using +=
.
element.className += ' bar';
<div class="foo bar"></div>
Replace all the classes by setting className
to a new value.
element.className = 'center padded';
<div class="center padded"></div>
Using Class classList
classList
is the most comprehensive way to add, toggle and remove classes in JavaScript. Let's look at some basic usage examples before delving into the other functionalities it offers.
<div class="foo bar"></div>
const element = document.querySelector('.foo');
Get all existing classes:
element.classList
["foo", "bar", value: "foo bar"]
classList
returns an array of the classes inside a DOMTokenList
object. If we wanted to get the first class we can get the first element in the array by its index:
element.classList[0]
foo
Since classList
returns an array of the classes we can count them by using .length
.
element.classList.length
2
classList item() Method
We can use the item()
method to get a class by its array index value. It returns undefined
if the index does not exist.
element.classList.item(0)
foo
classList add() Method
Single or multiple classes can be added to the HTML element using the classList
add()
method.
element.classList.add('margin-left', 'flex', 'center')
<div class="foo bar margin-left flex center"></div>
note - if you attempt to add classes that already exist on the element, they will be ignored by add()
classList contains() Method
To find if a class name exists on an element, you can use the contain()
method. It returns true
or false
.
<div class="foo bar"></div>
const element = document.querySelector('.foo');
element.classList.contains('stuff');
false
classList remove() Method
To remove one or multiple classes use the remove()
method. If you try to remove class names that don't exist on an HTML element no errors will be thrown, it will just skip them.
element.classList.remove('bar');
<div class="foo"></div>
classList toggle() Method
toggle()
is a handy method for toggling classes. It works just like the jQuery toggleClass()
method and will save you having to determine if an element has a class and adding or removing it.
element.classList.toggle('bar');
toggle()
will also tell you if an element was added or removed. It returns true
if it added the class and false
if it was removed.
<div class="foo"></div>
const element = document.querySelector('.foo');
const added = element.classList.toggle('bar');
<div class="foo bar"></div>
console.log(added);
true
classList replace() Method
The replace()
method can be used to replace a class name. The first argument is the existing class and the second is the name to replace it with. This method will return true
or false
depending on whether it could replace the existing class.
element.classList.replace('bar', 'kk');
classList forEach() Method
You call iterate over classes using forEach
like this:
element.classList.forEach((item, index) => {
console.log(item);
});
foo
bar
Conclusion
JavaScript has improved vastly in the last decade when it comes to common solutions web developers need to implement. You now know that DOM manipulations can be done in vanilla JavaScript in a way that is just as readable as jQuery and it may make you consider whether you need jQuery at all for some applications.