JAVASCRIPT
Toggle CSS Classes for Dynamic Styling and State
Dynamically add, remove, or toggle CSS classes on DOM elements using JavaScript `classList` API, enabling interactive styling and UI state changes.
const toggleButton = document.getElementById('toggle-btn');
const targetBox = document.getElementById('target-box');
if (toggleButton && targetBox) {
toggleButton.addEventListener('click', () => {
// Toggles the 'active' class
targetBox.classList.toggle('active');
console.log(`'active' class is now: ${targetBox.classList.contains('active') ? 'present' : 'absent'}`);
// Example: add a class if not present
if (!targetBox.classList.contains('highlight')) {
targetBox.classList.add('highlight');
console.log('Added highlight class.');
}
// Example: remove a class
setTimeout(() => {
targetBox.classList.remove('highlight');
console.log('Removed highlight class after 2 seconds.');
}, 2000);
});
} else {
console.error('Toggle button or target box not found!');
}
How it works: This snippet illustrates how to manipulate an element's CSS classes using the `classList` API. `classList.toggle()` is particularly useful for switching between states, such as showing/hiding content or applying/removing an active style. `classList.add()` and `classList.remove()` allow explicit addition or removal of classes. This is a common pattern for managing dynamic styling and UI states without directly manipulating inline styles.