How to Remove Class in JavaScript: Simple Guide
To remove a class from an HTML element in JavaScript, use the
element.classList.remove('className') method. This removes the specified class from the element's class list if it exists.Syntax
The syntax to remove a class from an element is simple:
element: The HTML element you want to change.classList: A property that holds all classes of the element.remove('className'): The method that removes the specified class.
javascript
element.classList.remove('className');Example
This example shows how to remove the class highlight from a paragraph when a button is clicked.
javascript
const paragraph = document.querySelector('p'); const button = document.querySelector('button'); button.addEventListener('click', () => { paragraph.classList.remove('highlight'); console.log('Class removed:', paragraph.className); });
Output
Class removed:
Common Pitfalls
Some common mistakes when removing classes include:
- Trying to remove a class that does not exist (no error, but no change).
- Using
element.className = ''which removes all classes instead of just one. - Forgetting to select the correct element before removing the class.
javascript
/* Wrong way: removes all classes */ element.className = ''; /* Right way: removes only one class */ element.classList.remove('className');
Quick Reference
| Method | Description |
|---|---|
| element.classList.remove('className') | Removes the specified class from the element. |
| element.classList.add('className') | Adds a class to the element. |
| element.classList.contains('className') | Checks if the element has the class. |
| element.className = '' | Removes all classes from the element (use carefully). |
Key Takeaways
Use element.classList.remove('className') to remove a specific class safely.
Removing a class that does not exist does nothing and causes no error.
Avoid setting element.className = '' unless you want to remove all classes.
Always select the correct element before modifying its classes.
classList methods provide easy ways to manage CSS classes on elements.