JAVASCRIPT
Dynamically Add or Remove CSS Classes
Learn to efficiently add, remove, or toggle CSS classes on DOM elements using JavaScript's `classList` API for dynamic styling and interactive user interfaces.
// HTML: <button id="myButton" class="btn">Click me</button>
const button = document.getElementById('myButton');
// Add a class
button.classList.add('active'); // Now has classes "btn active"
// Remove a class
button.classList.remove('btn'); // Now has class "active"
// Toggle a class (adds if not present, removes if present)
button.classList.toggle('highlight'); // Adds 'highlight'
button.classList.toggle('highlight'); // Removes 'highlight'
// Check if a class exists
const hasActiveClass = button.classList.contains('active'); // true
console.log(button.className); // Output: "active" or "active highlight"
How it works: The `classList` property provides a simple way to access and manipulate an element's list of classes. Methods like `add()`, `remove()`, `toggle()`, and `contains()` make it easy to dynamically change an element's styling based on user interaction or application state without directly manipulating the `className` string, ensuring cleaner and more maintainable code.