Adding & Removing Classes
Learn how to change an element's appearance by toggling CSS classes with JavaScript — the clean, maintainable way to handle dynamic styles.
classList: your CSS wardrobe
Every element has a `.classList` property that lets you add, remove, and toggle CSS classes. This is the primary way JavaScript controls visual changes on a page.
- `element.classList.add('active')` — adds the class - `element.classList.remove('active')` — removes the class - `element.classList.toggle('active')` — adds it if missing, removes it if present - `element.classList.contains('active')` — returns `true` or `false`
When YouTube highlights the current video tab, that's `classList.add('active')`. When you close a dropdown menu, that's `classList.remove('open')`. When you click a dark mode toggle, that's `classList.toggle('dark')`.