freecoding.school100% FREE · NO SIGNUP
The Old NetISSUE #41 of 60

className · classList · the css hooks

Pixel PeteVSQuirks Mode
Pixel Pete saysclassName and classList manage an element’s CSS classes — classList is the clean API.

el.className is the whole class string (overwriting it clobbers other classes). el.classList is the surgical API: add, remove, toggle, contains. Driving appearance by toggling classes (styled in CSS) is the DHTML pattern that aged best — it keeps logic and presentation separate.

Power-ups you unlock

Quirks Mode attacks — common mistakes

Boss battleToggle an "open" class on click and style it in CSS.

Example code

<!doctype html><html><head><meta charset="utf-8"><style>.open{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('open');</script></body></html>
▶ Open the interactive comic issue
‹ Computed Styles · GetComputedStyleSetAttribute · GetAttribute · RemoveAttribute ›