JAVASCRIPT
Toggle CSS Classes on Elements
Learn to effortlessly add, remove, or toggle CSS classes on DOM elements using JavaScript's classList API, enabling dynamic styling based on user interaction.
const toggleButton = document.getElementById('toggleBtn');
const targetElement = document.getElementById('myBox');
toggleButton.addEventListener('click', () => {
targetElement.classList.toggle('active');
if (targetElement.classList.contains('active')) {
console.log('Element is now active.');
} else {
console.log('Element is no longer active.');
}
});
How it works: This snippet demonstrates how to dynamically toggle CSS classes on an HTML element. When a button is clicked, the 'classList.toggle()' method is used to add or remove the 'active' class from a target element, allowing for responsive styling changes. It also shows checking for the class's presence.