Skip to content
Clairos Learn

DOM and events · Lesson 6 of 10 · 7 minutes

DOM and events: Class toggles

classList.toggle alternates membership unless given an explicit force boolean.

Mastery 0/3Run itExplain itApply it
Web workshopInert preview · code inspection

Current edit

PreviewNo external resources

Understand the pattern

classList.toggle alternates membership unless given an explicit force boolean.

classList.toggle alternates membership unless given an explicit force boolean.

Misconceptions to reject

  • A string containing code executes automatically when it is assigned.
  • A successful element lookup guarantees that the rest of an event handler is correct.

This is a code-inspection lab, not a full JavaScript runtime.

Worked example and expected result
const button = document.querySelector("#start");
const panel = document.querySelector("#panel");
if (button && panel) { button.addEventListener("click", () => { panel.classList.toggle("expanded"); }); }

classList.toggle alternates membership unless given an explicit force boolean.

Try a variation

Adapt the final example to a different project name while retaining its structure and relationships. A different context still needs a real browser and accessibility check.

Explain it

Which statement correctly explains class toggles?

Apply it elsewhere

You reuse class toggles in a different project. What must still be verified?

Keep the momentum.

Complete the lab, then explain and apply the pattern.

Next: DOM and events: Data attributesTry an incident drill

Anonymous lesson and mastery progress lasts for this session. Sign in to keep synced lesson XP between sessions; mastery stays device-local. No speed bonus, lost lives, or hint penalties.

Keep learning

  1. 01DOM and events: Class additionsclassList.add adds a class without replacing unrelated classes already on the element.Practice
  2. 02DOM and events: Data attributesdataset exposes data-* values as strings; data-lesson-id becomes dataset.lessonId.Practice
  3. 03DOM and events: Keyboard-friendly buttonsA native button already supports keyboard activation. A click listener can serve mouse, touch, and keyboard users.Practice