JAVASCRIPT

Toggle CSS Class on Element

Learn to dynamically add, remove, or toggle CSS classes on HTML elements using JavaScript's `classList` API for interactive UI updates and styling.

function toggleElementClass(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: <div id="myBox" class="initial-style">Hello</div>
// And a CSS class: .active { background-color: yellow; border: 2px solid orange; }

// To add 'active' class:
// toggleElementClass('myBox', 'active');

// To remove 'active' class (if present):
// toggleElementClass('myBox', 'active');

// To explicitly add (ensuring it's there):
// document.getElementById('myBox').classList.add('another-class');

// To explicitly remove (ensuring it's gone):
// document.getElementById('myBox').classList.remove('initial-style');
How it works: This snippet demonstrates how to manipulate an element's CSS classes using the `classList` API. The `toggle()` method is particularly useful as it adds the class if it's not present or removes it if it is. This is ideal for interactive UI elements like toggling active states, visibility, or styling. `classList.add()` and `classList.remove()` offer explicit control for adding or removing specific classes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs