Script Valley
JavaScript in the Browser: DOM, Events & APIs
Styles, Classes, and Layout via JavaScriptLesson 3.1

How to add, remove, and toggle CSS classes with classList

classList API, add, remove, toggle, contains, replace, multiple classes, CSS state management

classList API

The classList property exposes a live DOMTokenList that lets you manipulate an element's class attribute without touching the full string.

const card = document.querySelector('.card');

card.classList.add('active');          // add one class
card.classList.add('highlighted', 'expanded'); // add multiple
card.classList.remove('disabled');     // remove one
card.classList.toggle('open');         // add if absent, remove if present
console.log(card.classList.contains('active')); // true / false
card.classList.replace('old-class', 'new-class');

toggle with a Boolean

Pass a second boolean argument to force-add or force-remove regardless of current state:

// Force-add 'hidden' when isHidden is true, remove when false
el.classList.toggle('hidden', isHidden);

Why Classes Instead of Inline Styles?

Keeping visual logic in CSS and behavioural logic in JavaScript maintains separation of concerns. You write the visual state once in CSS (.active { background: #333 }) and toggle the class from JavaScript. Changing a CSS variable in one place updates every element that uses it — impossible to do cleanly with inline styles.

Up next

Reading and setting inline styles with element.style

Sign in to track progress