← Back to all snippets
JAVASCRIPT

Add, Remove, and Toggle CSS Classes

Learn to dynamically manage CSS classes on DOM elements, adding, removing, or toggling them to control styling and visibility with JavaScript's classList API.

function manageElementClasses(elementId, action, className) {
  const element = document.getElementById(elementId);
  if (!element) {
    console.error(`Element with ID '${elementId}' not found.`);
    return;
  }

  switch (action) {
    case 'add':
      element.classList.add(className);
      console.log(`Added class '${className}' to #${elementId}.`);
      break;
    case 'remove':
      element.classList.remove(className);
      console.log(`Removed class '${className}' from #${elementId}.`);
      break;
    case 'toggle':
      const toggled = element.classList.toggle(className);
      console.log(`${toggled ? 'Added' : 'Removed'} class '${className}' on #${elementId}.`);
      break;
    case 'has':
      const hasClass = element.classList.contains(className);
      console.log(`Element #${elementId} ${hasClass ? 'has' : 'does not have'} class '${className}'.`);
      return hasClass;
    default:
      console.warn(`Invalid action '${action}'. Use 'add', 'remove', 'toggle', or 'has'.`);
  }
  return undefined;
}

// Usage example:
// Assuming a <div id="myBox" class="initial-class"></div>
// manageElementClasses('myBox', 'add', 'active'); // Adds 'active'
// manageElementClasses('myBox', 'remove', 'initial-class'); // Removes 'initial-class'
// manageElementClasses('myBox', 'toggle', 'highlight'); // Toggles 'highlight'
// const isActive = manageElementClasses('myBox', 'has', 'active'); // Checks if 'active' exists
How it works: The `manageElementClasses` function provides a convenient interface for manipulating an element's CSS classes using the `classList` API. It takes an element's ID, an action ('add', 'remove', 'toggle', 'has'), and the class name. `element.classList.add()` adds a class, `element.classList.remove()` removes one, and `element.classList.toggle()` adds it if not present or removes it if present. `element.classList.contains()` checks for its existence. This is a clean and efficient way to control an element's styling and behavior dynamically.

Need help integrating this into your project?

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

Hire DigitalCodeLabs