Note: There’s no need to add multiple classes in practice. One class is good enough, provided you’re smart with your classes (don’t worry, you’ll see why and how when we build components together).
Removing a class
To remove a class, you use the remove method, which is present in classList.
Element.classList.remove('className')
Here’s how you would remove the red class from a paragraph of text:
<p class="red">This is a paragraph</p>
const p = document.querySelector('p')
p.classList.remove('red')
If you check the DOM, you should see a paragraph without the red class:
Note: You don’t need to add . before your classes when you use Element.classList. This is a common mistake if you mix up the syntax for querySelector and Element.classList.
Removing multiple classes at once
You can remove multiple classes at one go by passing extra classes as arguments:
As before, you won’t have to remove multiple classes. A single class would do, provided you’re smart with your classes.
Checking if a class exists
If you want to check if a class exists, you can use the contains method:
Element.classList.contains('className')
This method is often used together with the if statement to check whether the class exists:
const div = document.querySelector('div')
if (div.classList.contains('superpower')) {
// Do something if the div has the class '.superpower'
}
Toggling a class
Toggling classes means this:
Remove .red if .red exists
Add .red on if .red does not exist
You can toggle a class manually with if/else statements:
if (element.classList.contains('red')) {
element.classList.remove('red')
} else {
element.classList.add('red')
}
You’ll toggle class on/off frequently when you build components—so much that JavaScript provides you with a toggle method that does exactly the same thing.
element.classList.toggle('red')
Exercise
Practice adding, removing, checking for classes and toggling classes with Element.classList. Work through the examples in this HTML:
<div class="add">Add a "red" class to me!</div>
<div class="remove">Remove the class, "remove" from me!</div>
<div class="contains1">Do I have a "blue" class?</div>
<div class="contains2 blue">Do I have a "blue" class?</div>
<div class="toggle">Do I have a "red" class? If yes, remove it. If no, add it.</div>