HTML:DOM classList API: add, remove, and toggle CSS Classes
HTML•Class Manipulation

DOM classList API: add, remove, and toggle CSS Classes

Separate style from logic: keep CSS definitions in stylesheets and toggle them via classList.toggle().

Syntax

el.classList.add("active"); el.classList.toggle("dark");

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
classList.toggle()MethodAdds class if absent, removes if present.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing HTML locally:

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; padding: 20px; transition: background 0.3s; }
    .dark-mode { background: #0f172a; color: white; }
    .theme-btn { padding: 10px 18px; border-radius: 6px; border: 1px solid #cbd5e1; cursor: pointer; font-weight: bold; }
  </style>
</head>
<body>
  <h2>Theme Toggle Demonstration</h2>
  <button id="theme-btn" class="theme-btn">Toggle Dark Mode</button>

  <script>
    const themeBtn = document.querySelector("#theme-btn");
    themeBtn.addEventListener("click", () => {
      document.body.classList.toggle("dark-mode");
    });
  </script>
</body>
</html>
Expected Output:
[Interactive UI: Clicking Button Seamlessly Toggles Document Background Between Light and Dark Mode]

How It Works: Step-by-Step

  • Lines 5-6: Defines .dark-mode CSS class.
  • Lines 15-18: classList.toggle("dark-mode") adds or removes class on click.

Key Concepts

  • classList.toggle() eliminates manual boolean tracking.
  • Modifying classes is cleaner and more maintainable than writing inline style attributes.

Common Mistake: Mutating className as a string (el.className += " active")

String concatenation easily introduces missing space bugs ("btnactive"). Use classList.add().

❌ Incorrect
el.className += "active"; // Results in "btnactive"!
✅ Correct
el.classList.add("active");

Related HTML Tutorials & Compiler

Run and test HTML on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

HTML Online Compiler