JAVASCRIPT

Toggle a CSS Class for Dynamic Styling

Discover how to efficiently add or remove a CSS class from an HTML element using JavaScript's `classList.toggle()`, perfect for interactive UI elements and state changes.

const myButton = document.getElementById('myButton');
const myDiv = document.getElementById('myDiv');

myButton.addEventListener('click', () => {
    myDiv.classList.toggle('active');
    // Example CSS for context:
    // .active { background-color: lightblue; border: 2px solid blue; padding: 10px; }
    // #myDiv { background-color: lightgray; transition: all 0.3s ease; }
});

// Example HTML for context:
// <button id="myButton">Toggle Style</button>
// <div id="myDiv">This div's style will change.</div>
How it works: This snippet shows how to toggle a CSS class on an HTML element using `classList.toggle()`. When `myButton` is clicked, `myDiv` will either gain or lose the 'active' class. This is a common and efficient pattern for dynamically changing an element's appearance, showing/hiding content, or indicating a state change without directly manipulating inline styles, as the styling logic remains within your CSS.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs