JAVASCRIPT

Toggle Element Classes for Dynamic Styling

Master the `classList` API to easily add, remove, or toggle CSS classes on HTML elements, enabling dynamic styling and interactive UI components.

<style>
  .toggle-button { padding: 10px 20px; cursor: pointer; background-color: #f0f0f0; border: 1px solid #ccc; }
  .active { background-color: #28a745; color: white; border-color: #28a745; }
  .hidden { display: none; }
</style>

<button id="myButton" class="toggle-button">Toggle Active</button>
<div id="myContent" class="hidden" style="padding: 10px; margin-top: 10px; border: 1px solid #ddd;">This content will be toggled.</div>

<script>
  const myButton = document.getElementById('myButton');
  const myContent = document.getElementById('myContent');

  myButton.addEventListener('click', function() {
    // Toggle 'active' class on the button
    this.classList.toggle('active');
    
    // Toggle 'hidden' class on the content div
    myContent.classList.toggle('hidden');

    // You can also add/remove classes explicitly:
    // if (myButton.classList.contains('active')) {
    //   console.log('Button is active');
    // } else {
    //   console.log('Button is inactive');
    // }
    // myButton.classList.add('highlight');
    // myButton.classList.remove('highlight');
  });
</script>
How it works: The `classList` API provides a convenient way to manipulate an element's CSS classes. Instead of manually working with `className` strings, `classList` offers methods like `add()`, `remove()`, `toggle()`, and `contains()`. The `toggle()` method is particularly useful for switching between states, such as showing/hiding content or applying/removing an 'active' style. This approach separates styling from JavaScript logic, leading to cleaner and more maintainable code, as CSS rules define the actual appearance for each class.

Need help integrating this into your project?

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

Hire DigitalCodeLabs