JAVASCRIPT
Manage CSS Classes on DOM Elements
Learn to easily add, remove, and toggle CSS classes on HTML elements using JavaScript's 'classList' API, enabling dynamic styling changes and interactive UI elements.
const myElement = document.getElementById('myElement');
if (myElement) {
// Add a class
myElement.classList.add('active');
console.log('Class "active" added.');
// Remove a class
myElement.classList.remove('inactive');
console.log('Class "inactive" removed (if present).');
// Toggle a class (adds if not present, removes if present)
myElement.classList.toggle('highlight');
console.log('Class "highlight" toggled.');
// Check if a class exists
const hasActive = myElement.classList.contains('active');
console.log('Element has "active" class:', hasActive);
}
How it works: This snippet demonstrates the efficient use of the `classList` API to manage CSS classes on an HTML element. It shows how to `add()`, `remove()`, `toggle()`, and `contains()` classes, enabling dynamic styling and state changes based on user interaction or application logic without directly manipulating inline styles.