freecoding.school100% FREE · NO SIGNUP
The DOM ForestISSUE #8 of 21

classes · classList · add · remove · toggle

NodetteVSThe Event Bubbler
Nodette saysclassList adds, removes, and toggles CSS classes cleanly.

el.classList.add/remove/toggle/contains("name") manages classes without clobbering the whole className string. toggle returns whether the class is now present, and takes an optional force boolean. Driving state through classes (and styling them in CSS) keeps logic and presentation cleanly separated.

Power-ups you unlock

The Event Bubbler attacks — common mistakes

Boss battleToggle an "active" class on a button click and style it in CSS.

Example code

<!doctype html><html><head><meta charset="utf-8"><style>.active{color:#06040d;background:#b388ff}</style></head>
<body style="background:#06040d;color:#e6e0ff;padding:20px"><button id="b">toggle</button>
<script>const b=document.getElementById('b'); b.onclick=()=>b.classList.toggle('active');</script></body></html>
▶ Open the interactive comic issue
‹ Attributes · GetAttribute · SetAttribute · DatasetStyles · Element.Style · GetComputedStyle ›