How to add a class to a DOM element
By Flavio Copes
Learn how to add a class to a DOM element in JavaScript using the classList.add() method, plus how to remove one with classList.remove().
When you have a DOM element reference you can add a new class to it by using the add method of classList:
const button = document.querySelector('.buy-button')
button.classList.add('highlighted')
You can pass multiple classes at once:
button.classList.add('highlighted', 'pulsing')
If the element already has that class, nothing happens. classList never stores duplicates, so you can call add() without checking first.
You can remove a class using the remove method:
button.classList.remove('highlighted')
Why not use className?
Before classList, the way to add a class was string manipulation on the className property:
button.className += ' highlighted'
This is fragile. Forget the leading space and you merge the new class with the last existing one. Run it twice and you get the class listed twice.
classList handles all of that for you. There’s no reason to touch className for adding or removing a single class.
Other useful classList methods
toggle() adds the class if it’s missing, removes it if it’s there:
menu.classList.toggle('open')
contains() tells you if the element has a class:
button.classList.contains('highlighted') //true
replace() swaps one class for another in a single call:
alert.classList.replace('warning', 'success')
Implementation detail: classList is not an array, but rather it is a collection of type DOMTokenList.
You can’t directly edit classList because it’s a read-only property. You can however use its methods to change the element classes.
Be careful with spaces in class names
Each argument to add() must be a single class name. Pass a string containing a space and you get an exception:
button.classList.add('is active')
//Uncaught DOMException: the token contains invalid characters
The fix is passing the classes as separate arguments:
button.classList.add('is', 'active')
This usually bites when the class name comes from a variable built somewhere else in the code, so if you see that error, check what string you’re actually passing.
Related posts about platform: