JAVASCRIPT

Toggle CSS Class on an Element

Learn how to dynamically add or remove a CSS class from an HTML element using JavaScript's `classList.toggle()`, perfect for interactive UI elements like menus or modals.

function toggleCssClass(elementId, className) {
  const element = document.getElementById(elementId);
  if (element) {
    element.classList.toggle(className);
    console.log(`Class '${className}' toggled on element '${elementId}'. Current state: ${element.classList.contains(className) ? 'active' : 'inactive'}`);
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
  }
}

// Example usage:
// <button id="myButton" class="btn">Toggle Active</button>
// <div id="myDiv" class="hidden">Content</div>

// CSS:
// .active { background-color: yellow; }
// .hidden { display: none; }
// .visible { display: block; }

// document.getElementById('myButton').addEventListener('click', () => {
//   toggleCssClass('myDiv', 'hidden'); // Toggles display: none
//   toggleCssClass('myDiv', 'visible'); // Also works for other classes
//   toggleCssClass('myButton', 'active');
// });
How it works: This snippet demonstrates a common pattern for interactive web elements. It uses the `classList` property of an element, specifically the `toggle()` method, to add or remove a specified CSS class. This is highly useful for changing an element's style or visibility (e.g., showing/hiding a menu, activating a button) without directly manipulating inline styles, leveraging the power of CSS.

Need help integrating this into your project?

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

Hire DigitalCodeLabs