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:
| Parameter | Type | Description |
|---|---|---|
| classList.toggle() | Method | Adds class if absent, removes if present. |
Ready-to-Run Code Example
Executable in CompilraRun 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
DOM Manipulation: querySelector, textContent, and innerHTML
Select and manipulate HTML elements using document.querySelector and textContent.
DOM Event Listeners: addEventListener, Click, and Input Events
Respond to user actions using addEventListener for click, input, and keyup events.
Dynamic DOM: document.createElement and appendChild
Generate dynamic HTML elements on the fly with document.createElement and append.
HTML Online Compiler
Open in Compilra IDE
Run and test HTML on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.