beginner

Toggle CSS Class

Add and remove CSS classes from elements.

Class toggling with classList is fundamental for interactive UIs. This exercise teaches you modern DOM manipulation for styling changes, animations, and state management.

📚 Concepts & Theory

Toggling CSS classes is essential for interactive web applications. The classList API provides a modern, clean way to manipulate element classes.

Understanding classList:

classList Methods:

1. toggle() - Add or Remove

element.classList.toggle("active");
// If class exists, removes it
// If class doesn't exist, adds it

2. add() - Add Class

element.classList.add("highlight");
// Adds class if not present
// Does nothing if already exists

3. remove() - Remove Class

element.classList.remove("active");
// Removes class if present
// Does nothing if not exists

4. contains() - Check Presence

if (element.classList.contains("active")) {
// Class is present
}

5. replace() - Swap Classes

element.classList.replace("old", "new");

Multiple Classes:

element.classList.add("class1", "class2", "class3");
element.classList.remove("class1", "class2");

Old Way vs Modern Way:

❌ Old (String Manipulation):

element.className += " active";  // Problematic
element.className = element.className.replace("active", "");

✅ Modern (classList API):

element.classList.toggle("active");  // Clean and safe

Common Toggle Pattern:

button.addEventListener("click", () => {
menu.classList.toggle("open");
});

Conditional Toggle:

// Second parameter forces add (true) or remove (false)
element.classList.toggle("active", shouldBeActive);

Why classList is Better:

  • No string manipulation needed

  • Handles edge cases (duplicate classes, whitespace)

  • More readable and maintainable

  • Chainable: el.classList.add("a").remove("b")
Use Cases:
  • Show/hide elements (toggle "hidden" class)

  • Active states in navigation

  • Accordion/dropdown menus

  • Theme switching (dark/light mode)

  • Animation triggers

🎯 Your Challenge

Write a function to toggle the \"active\" class.

📝 Starter Code

JavaScript
// HTML: <button id="btn">Click me</button>

function toggleActive() {
  // Your code here
}
  • Use the classList property to access class manipulation methods
  • The toggle() method adds the class if missing, removes if present
  • No need for if statements - toggle does it automatically
  • Syntax: element.classList.toggle(className)
  • Don't include the dot (.) in the class name

Solution

JavaScript
function toggleActive() {
  const btn = document.getElementById('btn');
  btn.classList.toggle('active');
}

document.getElementById('btn').onclick = toggleActive;

Explanation

This solution uses the classList.toggle() method, which is the idiomatic way to add/remove classes in modern JavaScript. toggle() checks if the class exists on the element: if present, it removes it; if absent, it adds it. This is perfect for binary states like show/hide, active/inactive, or expanded/collapsed. The classList API is much cleaner than string manipulation of className and handles edge cases automatically (like duplicate classes or whitespace issues). Time complexity: O(1).

❓ Frequently Asked Questions

It returns true if the class was added, false if it was removed.
No, toggle() only works with one class. Call it multiple times or use add/remove for multiple classes.
Always use classList for class manipulation. className is for getting/setting the entire class string.
Use classList.add() to force add, or classList.remove() to force remove. Or use toggle(class, boolean).

🔗 Related Exercises