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()

1
2
3
4
5
6
7
const todoItem = document.querySelector('.todo-item');

if (todoItem.classList.contains('marked')) {
todoItem.classList.remove('marked');
} else {
todoItem.classList.add('marked');
}

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

.toggle()

1
2
3
4
5
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.

Tip: 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/