DEV Community 👩‍💻👨‍💻

Cover image for Difference Between classList and className
Mahabubur Rahman
Mahabubur Rahman

Posted on • Updated on • Originally published at microrony.hashnode.dev

Difference Between classList and className

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 like toggle and replace.

if (clicked) {
    button.classList.add('clicked');
} else {
    button.classList.remove('clicked');
}

Enter fullscreen mode Exit fullscreen mode

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 = '';
}

Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
nikhilmwarrier profile image
nikhilmwarrier • Edited on

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...

Collapse
 
microrony profile image
Mahabubur Rahman

My pleasure, Yes! toggle method is very useful.

Let's Get Wacky


Use any Linode offering to create something unique or silly in the DEV x Linode Hackathon 2022 and win the Wacky Wildcard category

Join the Hackathon <-