We use classList and className on JavaScript DOM to manipulate classes from the element. These two DOM property has different use cases. Let's see what is the main difference between them.
classList
Using
classList
, you can add or remove a class without affecting any other classes the element may have.So this is helpful for adding additional classes to an element that contain other classes.
classList
has some handy methods liketoggle
andreplace
.
if (clicked) {
button.classList.add('clicked');
} else {
button.classList.remove('clicked');
}
Here if the button was clicked it will add the clicked class along with other classes the element may have and it will remove only the clicked class from the element.
className
If you use
className
, it will wipe out any existing classes while adding the new one (or if you assign an empty string it will wipe out all of them).Using
className
can be a convenience when you know this element will not use any other classes.
if (clicked) {
button.className = 'clicked';
} else {
button.className = '';
}
In this case, className
will wipe all the classes the element may have and add clicked class to it. The empty string('') will wipe all the classes.
Conclusion
My recommendation would be to use
className
whenever possible.Use
classList
when you need classList methods like toggle, replace, etc.