JAVASCRIPT

Toggle CSS Classes for Dynamic UI States

Learn how to add, remove, and toggle CSS classes on DOM elements using JavaScript's classList API to manage dynamic UI states and apply styles effectively.

document.addEventListener('DOMContentLoaded', () => {
  const toggleButton = document.getElementById('toggle-button');
  const targetElement = document.getElementById('styled-box');

  if (toggleButton && targetElement) {
    toggleButton.addEventListener('click', () => {
      // Toggle a class: adds if not present, removes if present
      targetElement.classList.toggle('active');

      // Other classList methods:
      // targetElement.classList.add('highlight'); // Adds 'highlight' class
      // targetElement.classList.remove('inactive'); // Removes 'inactive' class
      // const hasClass = targetElement.classList.contains('active'); // Checks for 'active' class

      const isActive = targetElement.classList.contains('active');
      console.log('Element is now active:', isActive);
      toggleButton.textContent = isActive ? 'Deactivate' : 'Activate';
    });
  }
});
How it works: This snippet focuses on managing CSS classes, a fundamental way to change an element's appearance and state. It primarily uses `element.classList.toggle()` to add or remove a class based on its current presence, which is very common for interactive UI elements. It also briefly mentions `add()`, `remove()`, and `contains()` for more explicit control, demonstrating how JavaScript can drive visual changes defined in CSS without directly manipulating inline styles.

Need help integrating this into your project?

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

Hire DigitalCodeLabs