JAVASCRIPT

Toggling CSS Classes for Dynamic Styling

Master how to add, remove, or toggle CSS classes on DOM elements with JavaScript, enabling interactive styling changes like showing/hiding elements or applying active states.

// Get a reference to the button and the element to be toggled
const toggleButton = document.getElementById('toggleBtn'); // e.g., <button id="toggleBtn">Toggle Content</button>
const targetElement = document.getElementById('contentBox'); // e.g., <div id="contentBox" class="active">...</div>

// Define a CSS class, e.g., in your stylesheet:
// .hidden { display: none; }
// .highlight { border: 2px solid red; background-color: lightyellow; }

if (toggleButton && targetElement) {
  toggleButton.addEventListener('click', function() {
    // Toggle a class named 'hidden' on the target element
    targetElement.classList.toggle('hidden');

    // You can also toggle other classes, e.g., a 'highlight' class
    // targetElement.classList.toggle('highlight');

    // Change button text based on visibility
    if (targetElement.classList.contains('hidden')) {
      toggleButton.textContent = 'Show Content';
    } else {
      toggleButton.textContent = 'Hide Content';
    }
  });
} else {
  console.error('Toggle button or target element not found.');
}
How it works: This code demonstrates the use of `element.classList.toggle()` to add or remove a CSS class from an element dynamically. This is extremely useful for interactive UI components like toggling visibility, applying active states, or changing themes based on user actions. The button text is also updated to reflect the current state of the content box.

Need help integrating this into your project?

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

Hire DigitalCodeLabs