How to add, remove, and toggle CSS classes in JavaScript
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.
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:
The following example shows how to add a new CSS class or replace all existing CSS classes of the above
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.
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>
// 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.
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
pizza.classList.add('sauce', 'cheese', 'tomato')
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:
div class="hot spicy pizza cheese tomato"> 🍕 div>
console.log(pizza.classList.contains('cheese')) // true console.log(pizza.classList.contains('yogurt')) // false
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.
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') >
pizza.classList.toggle('olive')
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
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 use remove() along with add() to replace a CSS class in older browsers.
// iterate over all classes pizza.classList.forEach((item, index) => console.log(item) >)
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.
You might also like.
How To Modify CSS Classes in JavaScript
Any web developer starts their journey by learning HTML, CSS, and JavaScript. HTML gives structure to our webpages, JavaScript is a web programming language that gives us the ability to interact with users whereas CSS gives us the ability to style our web applications and web pages. To manipulate and work with the CSS classes, JavaScript offers us classList and className properties that can be used to manipulate the class attribute.
The class name can be used by JavaScript to manipulate the specified element while CSS uses that class name to style that element. Hence, in this post, we will go through how to modify CSS classes in JavaScript but first let us set the environment by initializing elements in HTML and then styling that element in CSS.
Environment Set up
Let us create a div element that works like a container and place two elements inside this container. One will be the h2 tag and the other will be the p tag. To link the CSS file to this HTML we have inserted a link tag in the head and referenced our CSS file inside the href attribute (style.css):
Modify CSS using JavaScript < / title >
The capital of England is London < / p >
To get the reference of the div element inside CSS, we have used the class attribute. We performed some styling on the div container as well as the elements inside the div container.
.container {
background-color : rgb ( 54 , 224 , 207 ) ;
}
.containerh2 , p {
color : rgb ( 125 , 104 , 184 ) ;
}
The output will look like this:
Modify CSS Classes
As mentioned in the introductory part of this article, JavaScript offers us classList and className properties that can be used to manipulate the class attribute.The className is used to set a value to a class directly whereas using the classList property we can perform the following functions:
- classList.add() is used to add class values
- classList.toggle() is used to turn on or off a class
- classList.replace() is used to replace a class value with another class value
- classList.contains() is used to check whether a value exists or not
- classList.remove() is used to remove a class value
Let us go through an example to better understand the classList property and its built-in methods and we will use the same HTML and CSS code that we used earlier. First, let us use the className property to assign a class to the h2 attribute. For that purpose we have referenced a class in CSS that doesn’t exist at the moment and give it some styling shown below:
Next, get the reference of the h2 element using the querySelector(‘h2’) which will select the first h2 element in the HTML code. Next, use the className property to assign the info class to the h2 element. The JavaScript code is given below:
// Select first h2 element
const myh2 = document. querySelector ( ‘h2’ ) ;
// Set the info class to myh2
myh2. className = ‘info’ ;
To reference this JavaScript code use the script tag with src attribute in the HTML code giving the JavaScript file name in src attribute:
The code.js is our JavaScript file name. Our web page will now look like this:
Let us now modify the CSS classes using the classList property. As seen earlier, the classList property offers us some built-in methods that we can use to modify CSS classes. We will use the classList.add() which will add a class in the following example:
const hideDiv = document. querySelector ( ‘div’ ) ;
hideDiv. classList . add ( ‘hidden’ ) ; // hidden class added
Next, go to the CSS file and initialize the hidden class by making the display none so that the div is not visible:
Now you will see that the div element will be hidden and you will not see anything on your webpage:
Let us now use the classList.replace() method where we will replace the existing hidden class with another class wrap.
const hideDiv = document. querySelector ( ‘div’ ) ;
hideDiv. classList . add ( ‘hidden’ ) ; // hidden class added
hideDiv. classList . replace ( ‘hidden’ , ‘wrap’ ) ; // replace hidden class with info class
Next, go to your CSS file and style the wrap class:
You will now see that our content is now visible and the font size will be larger than before:
Conclusion
JavaScript offers us two properties that we can use to modify CSS classes; classList and className property. The className property is used to set a value to a CSS class directly whereas the classList gives us some built-in methods to manipulate the CSS classes.
For example, the classList.add() gives us the ability to add class values, classList.remove() gives us the ability to remove a class, classList.toggle() gives us the ability to add toggling to a class and the classList.replace() gives us the ability to replace a class value with another class.
In this post, we saw how to modify CSS classes using JavaScript by learning about two properties of JavaScript; classList and className.
About the author
Shehroz Azam
A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.