Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to add, remove or toggle a CSS class

Short answer

The classList property has methods for all class operations:

<style>.active { color: crimson; font-weight: bold; }</style>
<p id="text">Click the buttons</p>
<button id="add">add</button>
<button id="remove">remove</button>
<button id="toggle">toggle</button>
<script>
  const text = document.getElementById('text');
  document.getElementById('add').onclick = () => text.classList.add('active');
  document.getElementById('remove').onclick = () => text.classList.remove('active');
  document.getElementById('toggle').onclick = () => text.classList.toggle('active');
</script>

By a condition

The second argument of toggle() forces the class on or off:

input.classList.toggle('invalid', input.value.trim() === '');

Checking and replacing

contains() checks a class, replace() swaps one class for another:

if (button.classList.contains('primary')) {
  button.classList.replace('primary', 'secondary');
}

Common mistake

Assigning to className replaces all classes of the element at once. Use classList to change just one:

// before: class="button large"
button.className = 'active'; // after: class="active", the others are gone

Thanks for reading!

Donate to the site — we work hard for you.