JAVASCRIPT

Toggle a CSS Class for Interactive Elements

Learn how to easily add or remove a CSS class from an HTML element using JavaScript's classList API, perfect for interactive UI states.

function toggleClass(elementId, className) {
  const element = document.getElementById(elementId);
  if (element) {
    element.classList.toggle(className);
    console.log(`Class '${className}' toggled on element '${elementId}'.`);
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
  }
}

// Example Usage:
// Assume you have an HTML element like <div id="myDiv" class="active">Hello</div>
// toggleClass('myDiv', 'active'); // Removes 'active'
// toggleClass('myDiv', 'highlight'); // Adds 'highlight'
How it works: This snippet provides a reusable function to toggle (add if not present, remove if present) a specific CSS class on an HTML element identified by its ID. It leverages the `classList.toggle()` method, which is a convenient way to manage an element's classes for dynamic styling, such as showing/hiding elements or changing their appearance based on user interaction.

Need help integrating this into your project?

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

Hire DigitalCodeLabs