Back to JavaScript Fundamentals

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.
5 min readLogan FordLogan Ford
How to add or remove CSS classes with JavaScript

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 classes
  • remove(): Removes one or more classes
  • toggle(): Adds a class if it's absent, removes it if present
  • contains(): Checks if an element has a specific class
  • replace(): 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');
3
4button.addEventListener('click', () => {
5 // Add multiple classes at once
6 container.classList.add('active', 'highlight');
7
8 // Check if class was added successfully
9 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');
3
4closeButton.addEventListener('click', () => {
5 try {
6 modal.classList.remove('visible', 'animate');
7
8 // Add a callback after animation ends
9 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');
3
4menuButton.addEventListener('click', () => {
5 // Toggle multiple classes with a single call
6 navigation.classList.toggle('visible');
7 navigation.classList.toggle('expanded');
8
9 // Update button accessibility
10 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;
3
4themeToggle.addEventListener('click', () => {
5 // Check current theme
6 const isDarkMode = body.classList.contains('dark-theme');
7
8 // Replace theme classes
9 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 }
16
17 // Update UI elements
18 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:

  1. 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
  1. 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 practice
2element.className = 'new-class'; // This will overwrite all existing classes
3
4// Good practice
5element.classList.add('new-class');
6element.classList.remove('old-class');

Common Mistakes When Manipulating Classes

  1. 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 practice
2element.className = 'new-class'; // This will overwrite all existing classes
3
4// Good practice
5element.classList.add('new-class');
6element.classList.remove('old-class');
  1. 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 practice
2element.classList.toggle('active'); // This will toggle the class without checking the current state
3
4// Good practice
5if (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.

Share this article