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 aadd
only orremove
only function by supplying theforce
flag as a second parameter. \O/