JAVASCRIPT
Dynamically Add, Remove, and Toggle CSS Classes
Master JavaScript's `classList` API to effortlessly manipulate an element's CSS classes, enabling dynamic styling and interactive UI changes.
const myElement = document.getElementById('myElement');
// Add a class
myElement.classList.add('active');
// Remove a class
myElement.classList.remove('hidden');
// Toggle a class (add if not present, remove if present)
myElement.classList.toggle('selected');
// Check if a class exists
if (myElement.classList.contains('active')) {
console.log('Element has the active class.');
}
How it works: This code showcases the `classList` API, a convenient way to manage an element's CSS classes. Instead of manipulating `className` as a string, `classList.add()`, `classList.remove()`, and `classList.toggle()` provide direct methods for class manipulation. `classList.contains()` allows checking for the presence of a class, making dynamic styling and UI state management straightforward and robust.