JAVASCRIPT
Toggle a CSS Class on a DOM Element
Efficiently add or remove a CSS class from an HTML element using JavaScript's classList API, perfect for interactive styling and dynamic UI changes.
function toggleCssClass(elementId, className) {
const element = document.getElementById(elementId);
if (element) {
element.classList.toggle(className);
} else {
console.warn(`Element with ID "${elementId}" not found.`);
}
}
// Usage example:
// Assuming <button id="myButton" class="default-style">Click me</button> in HTML
// And CSS: .active { background-color: yellow; font-weight: bold; }
// const myButton = document.getElementById('myButton');
// if (myButton) {
// myButton.addEventListener('click', () => toggleCssClass('myButton', 'active'));
// }
How it works: This snippet utilizes the `classList` API, specifically the `toggle()` method, to add or remove a CSS class from an element. If the class is present, it's removed; if not, it's added. This is a clean and efficient way to manage an element's styling based on user interaction or application state, commonly used for active states, menu toggles, or light/dark themes.