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.
Top comments (2)
Thanks, it really used to drive me crazy...
A quick tip:
You can add a simple attribute to toggle an element's class on an event like this:
<p class="open" onclick="this.classList.toggle('open')" >
This will check if it has the closed tag, and remove it if it exists, or add it if it doesn't, every time it is clicked...
A really nifty hack which can save quite some if-elses...
My pleasure, Yes! toggle method is very useful.