Lesson 9: Class Manipulation with classList

Learning Objectives

By the end of this lesson, learners will be able to:

  • Use classList methods to dynamically change CSS classes
  • Add, remove, toggle, or check for classes on an element
  • Build interactivity, such as showing/hiding content, or theme switching
  • Apply these concepts to build responsive, interactive components

Why Manipulate Classes?

In modern web development, the CSS class of an element controls:

  • Its appearance
  • Its visibility
  • Its layout

If you can change these classes with JavaScript, you can:
✅ Show/hide things
✅ Toggle themes
✅ Indicate active states
✅ Animate elements

That’s what classList is for: it’s a built-in JavaScript property that lets you easily work with classes on any element.


Using classList Methods

.add(className)

Adds a class to the element.

element.classList.add("highlight");

.remove(className)

Removes a class from the element.

element.classList.remove("hidden");

.toggle(className)

If the class is there, it removes it.
If the class is not there, it adds it.

element.classList.toggle("active");

✅ Great for on/off switches.


.contains(className)

Checks whether an element currently has the class.

if (element.classList.contains("dark")) {
  console.log("Dark mode is active");
}

Example: Toggling a Navigation Menu

Let’s say you have a mobile menu with a hamburger icon:

HTML:

<button id="menu-btn">☰ Menu</button>
<nav id="main-nav" class="hidden">
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="#">Contact</a>
</nav>

CSS:

.hidden {
  display: none;
}

.visible {
  display: block;
}

JavaScript:

let button = document.getElementById("menu-btn");
let nav = document.getElementById("main-nav");

button.addEventListener("click", function() {
  nav.classList.toggle("hidden");
  nav.classList.toggle("visible");
});

When the user clicks the button:

  • The class hidden is toggled off
  • The class visible is toggled on
  • Or vice versa

Other Use Cases

  • Dark mode
document.body.classList.toggle("dark-mode");
  • Highlighting active menu items
clickedItem.classList.add("active");
  • Error or success indicators
input.classList.add("error");
input.classList.remove("error");

Practice Challenge

HTML:

<button id="theme-btn">Toggle Dark Mode</button>

CSS:

.dark-mode {
  background-color: black;
  color: white;
}

JavaScript Task:

  • When the button is clicked, toggle the dark-mode class on the entire body.

Example:

let button = document.getElementById("theme-btn");

button.addEventListener("click", function() {
  document.body.classList.toggle("dark-mode");
});

Summary

MethodWhat it Does
.add()Adds a class
.remove()Removes a class
.toggle()Adds if missing, removes if present
.contains()Checks if the class is currently applied