JAVASCRIPT
Toggle CSS Class for Dynamic Styling
Learn to dynamically add or remove CSS classes from DOM elements using JavaScript's classList API for interactive UI updates and state management.
const element = document.getElementById('myElement');
// Add a class
element.classList.add('active');
// Remove a class
element.classList.remove('inactive');
// Toggle a class (adds if not present, removes if present)
element.classList.toggle('highlight');
// Check if a class exists
if (element.classList.contains('active')) {
console.log('Element has the active class.');
}
How it works: This snippet demonstrates how to manipulate an element's CSS classes using the `classList` API. `add()` appends a class, `remove()` deletes one, and `toggle()` intelligently adds or removes a class based on its current presence. `contains()` allows checking for a class without complex string parsing. This is crucial for dynamic styling based on user interaction or application state.