By the end of this lesson, learners will be able to:
classList methods to dynamically change CSS classesIn modern web development, the CSS class of an element controls:
If you can change these classes with JavaScript, you can:
✅ Show/hide things
✅ Toggle themes
✅ Indicate active states
✅ Animate elements
That’s what
classListis for: it’s a built-in JavaScript property that lets you easily work with classes on any element.
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");
}
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:
hidden is toggled offvisible is toggled ondocument.body.classList.toggle("dark-mode");
clickedItem.classList.add("active");
input.classList.add("error");
input.classList.remove("error");
HTML:
<button id="theme-btn">Toggle Dark Mode</button>
CSS:
.dark-mode {
background-color: black;
color: white;
}
JavaScript Task:
dark-mode class on the entire body.Example:
let button = document.getElementById("theme-btn");
button.addEventListener("click", function() {
document.body.classList.toggle("dark-mode");
});
| Method | What 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 |