Adding Classes with classList
You'll learn how to efficiently manage CSS classes on DOM elements using the modern classList API.
When you selected elements and set attributes in previous lessons, you gained control over individual properties. But CSS classes are special—elements often have multiple classes at once, and you need to add, remove, or toggle them without accidentally destroying the others. That's where classList shines.
Think of classList like a toolbox specifically designed for class management. Instead of manually parsing and reconstructing the className string (messy!), you get clean methods that handle the heavy lifting.
The classList Methods
Once you've selected an element, its classList property gives you these powerful tools:
add() – Adds one or more classes to the element
const box = document.getElementById('myBox');
box.classList.add('highlight');
box.classList.add('border', 'shadow'); // multiple at once
remove() – Removes specified classes
box.classList.remove('highlight');
toggle() – Adds the class if absent, removes it if present (perfect for show/hide patterns)
box.classList.toggle('active'); // switches back and forth
contains() – Checks if a class exists (returns true or false)
if (box.classList.contains('active')) {
console.log('Box is active!');
}
replace() – Swaps one class for another
box.classList.replace('old-theme', 'new-theme');
Why This Matters
These methods are safer and cleaner than string manipulation. They prevent duplicate classes, handle edge cases automatically, and make your intent crystal clear to anyone reading your code.
Key Takeaway: Use classList methods (add, remove, toggle, contains, replace) to manipulate element classes safely and efficiently—it's the modern, reliable way to control styling through JavaScript.