DOM Class List Toggle
Predict Output Medium
Question
What is the result?
Code
let el = document.createElement("div");
el.classList.add("active");
el.classList.toggle("active");
console.log(el.classList.contains("active"));
Hint
toggle removes the class if present, adds if absent.
Explanation
classList.add("active") adds the class. classList.toggle("active") then removes it (since it was present), returning false. classList.contains("active") checks if the class is present, returning false. toggle can also take a second argument to force add/remove: toggle("active", true) always adds.
Related Resources
Related Lessons
- DOM Manipulation
Learn DOM manipulation.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.