← Back to all snippets
JAVASCRIPT

Dynamic CSS Styling with JavaScript `classList` API

Control element styling by dynamically adding, removing, and toggling CSS classes using the powerful `classList` API for interactive UI updates, improving user experience.

// HTML Structure example:
// <button id="toggleButton" class="btn">Toggle Highlight</button>
// <div id="myElement" class="box">
//   This element's style will change.
// </div>

// CSS (example):
// .box {
//   border: 1px solid #ccc;
//   padding: 10px;
//   margin-top: 20px;
// }
// .highlight {
//   background-color: yellow;
//   border-color: gold;
//   font-weight: bold;
// }
// .active {
//   box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
// }

const toggleButton = document.getElementById('toggleButton');
const myElement = document.getElementById('myElement');

toggleButton.addEventListener('click', function() {
  // Toggle the 'highlight' class
  myElement.classList.toggle('highlight');

  // Add 'active' class only if 'highlight' is present
  if (myElement.classList.contains('highlight')) {
    myElement.classList.add('active');
  } else {
    myElement.classList.remove('active');
  }

  // You can also add/remove multiple classes at once
  // myElement.classList.add('class1', 'class2');
  // myElement.classList.remove('class3', 'class4');

  console.log('Current classes:', Array.from(myElement.classList).join(', '));
});
How it works: The `classList` API provides a convenient way to manipulate an element's CSS classes without directly modifying its `className` string. It offers methods like `add()`, `remove()`, `toggle()`, and `contains()` for precise control. This is the preferred method for applying dynamic styles based on user interactions or application state, as it cleanly separates JavaScript logic from CSS presentation and avoids issues with overwriting existing classes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs