The easiest and safest way to add, remove, or toggle an HTML element’s CSS class in JavaScript is using element.classList with .add(), .remove(), and .toggle(). It updates specific classes on an element cleanly without deleting or breaking any other CSS classes already attached to it.
How element.classList Works for Beginners
Every HTML element in the DOM has a classList property that manages its CSS classes like an organized list of names. If you change element.className directly, you can accidentally overwrite existing classes or mess up spaces between class names. Using classList lets you target one specific class at a time, which makes handling buttons, dropdowns, modals, and dark mode much simpler and less error-prone.
JavaScript
const box = document.querySelector(".info-box");
// 1. Add one or more classes at once
box.classList.add("active", "highlight");
// 2. Remove a class safely (no error if the class is not present)
box.classList.remove("highlight");
// 3. Toggle a class: adds it if missing, removes it if already there
box.classList.toggle("open");
// 4. Check whether a class is currently applied
console.log(box.classList.contains("active")); // true or false
Using .toggle() with a Condition
You can also pass a second boolean value (true or false) to .toggle(className, condition) to force a class on or off. When the condition is true, the class is added; when it is false, the class is removed. This keeps your UI state code clean and easy to read without extra if/else blocks.
JavaScript
const menu = document.querySelector(".side-menu");
const shouldShowMenu = true;
// Adds "visible" when true, removes it when false
menu.classList.toggle("visible", shouldShowMenu);
