JAVASCRIPT
Efficiently Toggling Multiple CSS Classes on an Element
Discover how to add or remove multiple CSS classes from an HTML element in a single operation, enabling dynamic styling based on user interaction or application state.
function toggleElementClasses(elementId, classesToToggle, condition) {
const element = document.getElementById(elementId);
if (!element) {
console.error(`Element with ID '${elementId}' not found.`);
return;
}
classesToToggle.forEach(className => {
element.classList.toggle(className, condition);
});
}
// Example Usage:
// Assume an HTML button: <button id="myButton" class="btn primary">Click Me</button>
// And some CSS:
// .btn { padding: 10px; border: 1px solid #ccc; }
// .primary { background-color: blue; color: white; }
// .active { border-color: green; font-weight: bold; }
// .warning { background-color: yellow; color: black; }
let isActive = false;
document.getElementById('myButton').addEventListener('click', () => {
isActive = !isActive;
toggleElementClasses('myButton', ['active', 'warning'], isActive);
console.log(`Button is now ${isActive ? 'active' : 'inactive'}`);
});
// You can also toggle based on a direct boolean value:
// toggleElementClasses('myButton', ['active'], true); // Adds 'active'
// toggleElementClasses('myButton', ['warning'], false); // Removes 'warning'
How it works: This snippet provides a reusable function to toggle multiple CSS classes on a given HTML element based on a boolean condition. It iterates through an array of class names and uses `element.classList.toggle(className, condition)`. The second argument to `toggle()` ensures that the class is added if `condition` is true, and removed if `condition` is false, making it very precise for state-driven styling without manual `add()` or `remove()` calls.