How to manipulate an element's classes in vanilla JS
In jQuery, there are several methods that allow you to manipulate the classes on an element. These are
hasClass(). Let’s look at how we can do these things using vanilla JS, and also how to replace a class—a method that jQuery lacks!
A note before we begin: you can and should still use the older
className property if it’s appropriate, but this post focuses on some newer methods available to the
For each of the following examples, let’s imagine you’ve selected an element and saved it to a variable called
app. You would call all of the following methods on the element’s
To add a class, you can use the
To remove a class, you can use the
To toggle a class, you can use the
Checking if an element has a class
To check for a class, you can use the
To replace a class, you can use the
This method, unlike the others in this post, accepts two arguments: the former being the old class, and the latter being the new class.
classList property is supported in all modern browsers, and IE10 and above. There are a few minor caveats, mostly for IE, so be sure to check the full browser compatibility information if this affects you.
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!