JAVASCRIPT
Toggle a CSS Class on an Element
Discover the simplest way to add or remove a CSS class from any HTML element using JavaScript's `classList.toggle()`, perfect for interactive UI elements.
function toggleElementClass(elementId, className) {
const element = document.getElementById(elementId);
if (element) {
element.classList.toggle(className);
} else {
console.error(`Element with ID '${elementId}' not found.`);
}
}
// Example usage:
// <button id="myButton" class="default-style">Click Me</button>
// <style>.default-style { background-color: lightblue; padding: 10px; } .highlight { background-color: yellow; font-weight: bold; }</style>
// toggleElementClass('myButton', 'highlight'); // Toggles 'highlight' class
How it works: This snippet provides a straightforward function to toggle a CSS class on an HTML element. It leverages the `classList` API, specifically the `toggle()` method, which adds the specified class if it doesn't exist, or removes it if it does. This is a common pattern for creating interactive UI components like active states, menu toggles, or light/dark mode switches.