How to add or remove CSS classes with JavaScript
Learn how to dynamically manipulate CSS classes using JavaScript's classList methods. Master adding, removing, and toggling classes with practical examples and best practices.


Getting Started with JavaScript Class Manipulation
Dynamic class manipulation is a fundamental skill for modern web development. By adding, removing, or toggling CSS classes with JavaScript, you can create interactive and responsive user interfaces. This guide will show you how to master class manipulation using the powerful classList
API.
The classList API Explained
The classList
property provides a powerful interface for manipulating CSS classes on HTML elements. It offers several methods:
add()
: Adds one or more classesremove()
: Removes one or more classestoggle()
: Adds a class if it's absent, removes it if presentcontains()
: Checks if an element has a specific classreplace()
: Replaces an existing class with a new one
Adding CSS Classes
Here's how to add a class when a button is clicked:
1const button = document.querySelector('.action-button');2const container = document.querySelector('.container');34button.addEventListener('click', () => {5 // Add multiple classes at once6 container.classList.add('active', 'highlight');78 // Check if class was added successfully9 if (container.classList.contains('active')) {10 console.log('Container is now active!');11 }12});
Removing CSS Classes
Here's a more advanced example of removing classes with error handling:
1const modal = document.querySelector('.modal');2const closeButton = document.querySelector('.close-button');34closeButton.addEventListener('click', () => {5 try {6 modal.classList.remove('visible', 'animate');78 // Add a callback after animation ends9 modal.addEventListener('transitionend', () => {10 modal.classList.remove('modal-open');11 }, { once: true });12 } catch (error) {13 console.error('Error removing classes:', error);14 }15});
Smart Class Toggling
Here's an enhanced example of class toggling with conditional logic:
1const menuButton = document.querySelector('.menu-toggle');2const navigation = document.querySelector('.nav-menu');34menuButton.addEventListener('click', () => {5 // Toggle multiple classes with a single call6 navigation.classList.toggle('visible');7 navigation.classList.toggle('expanded');89 // Update button accessibility10 const isExpanded = navigation.classList.contains('expanded');11 menuButton.setAttribute('aria-expanded', isExpanded);12 menuButton.textContent = isExpanded ? 'Close Menu' : 'Open Menu';13});
The classList.toggle()
method is particularly useful for interactive elements like menus, accordions, and modals. It automatically handles the state management for you, making your code more concise and maintainable.
Complex Class Manipulation Patterns
Here's an example combining multiple classList methods for complex interactions:
1const themeToggle = document.querySelector('.theme-toggle');2const body = document.body;34themeToggle.addEventListener('click', () => {5 // Check current theme6 const isDarkMode = body.classList.contains('dark-theme');78 // Replace theme classes9 if (isDarkMode) {10 body.classList.replace('dark-theme', 'light-theme');11 localStorage.setItem('theme', 'light');12 } else {13 body.classList.replace('light-theme', 'dark-theme');14 localStorage.setItem('theme', 'dark');15 }1617 // Update UI elements18 document.querySelectorAll('.theme-dependent')19 .forEach(element => {20 element.classList.toggle('dark-mode');21 });22});
Best Practices for Using classList in JavaScript While the classList API is powerful, it's important to follow best practices to keep your code clean and maintainable. Here are some tips:
- Avoid Repetitive DOM Queries. Instead of repeatedly querying the DOM for the same element, store the reference in a variable. This improves performance by reducing unnecessary DOM access.
1const button = document.querySelector('.action-button'); // Reusable reference
- Limit the Number of Class Changes. Changing classes too frequently (especially in animations) can impact performance. If possible, batch your class changes into a single classList.add() or classList.remove() call.
1// Bad practice2element.className = 'new-class'; // This will overwrite all existing classes34// Good practice5element.classList.add('new-class');6element.classList.remove('old-class');
Common Mistakes When Manipulating Classes
- Overusing className Instead of classList. Avoid manipulating classes directly with className if you're working with multiple classes. The classList API offers more flexibility and doesn’t overwrite existing classes.
1// Bad practice2element.className = 'new-class'; // This will overwrite all existing classes34// Good practice5element.classList.add('new-class');6element.classList.remove('old-class');
- Misusing toggle() Without Condition. The toggle() method is great, but without proper logic, it can lead to unexpected behavior. Always check the current state before toggling if you need specific control over the classes.
1// Bad practice2element.classList.toggle('active'); // This will toggle the class without checking the current state34// Good practice5if (element.classList.contains('active')) {6 element.classList.remove('active');7} else {8 element.classList.add('active');9}
Looking for more?
If you're looking for more examples and best practices, check out the classList documentation.
Or, why not check out our JavaScript fundamentals roadmap?
Land your dream tech job faster
Join 810+ developers who are accelerating their coding skills with TechBlitz.