JAVASCRIPT
Toggling CSS Classes on a DOM Element
Master how to add, remove, or toggle CSS classes on an HTML element using the classList API, enabling dynamic styling changes based on user interaction or application state.
const toggleButton = document.getElementById('myToggleButton');
const targetElement = document.getElementById('myStyledElement');
toggleButton.addEventListener('click', () => {
targetElement.classList.toggle('active');
if (targetElement.classList.contains('active')) {
console.log('The element now has the "active" class.');
} else {
console.log('The "active" class has been removed from the element.');
}
});
How it works: This snippet illustrates how to toggle a CSS class on an element using the `classList.toggle()` method. When `myToggleButton` is clicked, the `active` class is added to `myStyledElement` if it's not present, or removed if it is. This is incredibly useful for interactive UI elements that change appearance based on state.