AshKeys

Confessions and Confusions of Ashok M A. Personal and Professional Blog.

Ashok Mannolu Arunachalam, How toCSSJavaScript
Back

How to toggle a css class of an element

Sometimes, we want to mark the status of an element dynamically like from the JS.

An element's classList property contains the applied CSS classes. Through that we can toggle a class by using the following methods.

.add() or .remove()

js
const todoItem = document.querySelector('.todo-item')
if (todoItem.classList.contains('marked')) {
todoItem.classList.remove('marked')
} else {
todoItem.classList.add('marked')
}

You can supply an array of class values to be added or removed.

.toggle()

js
const todoItem = document.querySelector('.todo-item')
todoItem.classList.toggle('marked')
? console.log('Item marked!')
: console.log('Item unmarked!')

Yes, it returns a true when adding and false when removing a class.

It is possible to turn the toggle into a add only or remove only function by supplying the force flag as a second parameter. \O/