Struggling to manage the CSS classes dynamically through JavaScript? Say hi to your new best friend: the classList property, for easily adding, removing, and toggling classes on your DOM elements.
In this post, we'll cover:

What is classList  in JavaScript?

Why has it become so helpful?

How to use classList.add() and classList.contains()?

Common questions like, "Do JavaScript really have classes?" and "How does classList work in real-life examples?"

What is classList in JavaScript?

classList is a read-only property that provides methods of manipulating the class attribute of an HTML element. Instead of manually manipulating className which can be quite unwieldy, classList provides you with neater and easier methods of working with classes.

Here's a simple example:

<div id="myDiv" class="box"></div>

<script>
  const element = document.getElementById('myDiv');
  console.log(element.classList); // Output: DOMTokenList ['box']
</script>

With classList, you get a list of all the classes on the element, and you can manipulate them easily.


Adding Classes Made Simple

To add a new class to an element, use classList.add(). It’s as simple as this:

<button id="btn">Click me</button>

<script>
  const button = document.getElementById('btn');
  button.classList.add('active');
  console.log(button.classList); // Output: DOMTokenList ['active']
</script>

Add Multiple Classes

You can even add multiple classes in one go:

button.classList.add('primary', 'rounded');

Removing Classes

To remove a class, use classList.remove():

button.classList.remove('active');

Toggling Classes

To toggle a class (add it if it's not present, remove it if it is), use classList.toggle():

button.classList.toggle('highlight');

Chaining Methods

You can chain classList methods for more concise code:

button.classList.add('active').toggle('highlight');

This code first adds the active class and then toggles the highlight class.

Replacing a Class

While there's no direct replace() method, you can combine remove() and add() to achieve the same effect:

button.classList.remove('oldClass');
button.classList.add('newClass');

This code replaces the oldClass with newClass.


Check If a Class Exists

Ever wanted to check if an element has a specific class? use classList.contains():

<div id="box" class="highlight"></div>

<script>
  const box = document.getElementById('box');
  console.log(box.classList.contains('highlight')); // Output: true
</script>

This is super useful for conditional styling or logic.


Iterating Over Classes

You can iterate over the classes in a classList using a for...of loop:

for (const className of button.classList) {
  console.log(className);
}

This code will log each class name in the classList to the console.


Difference Between classList and className

Both classList and className allow you to manipulate CSS classes on elements. However, there are major differences between the two:

  • Ease of Use

    • classList allows for dynamic addition and removal of classes using methods like add(), remove(), toggle(), and contains().
    • className requires managing the entire class attribute as a string, which can lead to accidentally overwriting existing classes.
  • Readability

    • classList has a more readable, chainable, and declarative API
    • className often requires manual string concatenation or parsing, which can make code messy.
  • Performance

    • classList is optimized for adding or removing individual classes without affecting others.
    • className can be faster when you need to replace the entire class string at once, but it's less flexible.

Extra Tip: Use classList for fine class manipulations, and use className for simpler use cases where all classes are replaced at once.


Does JavaScript Have Classes?

Yes, JavaScript has classes, but they’re entirely different from CSS classes. In JavaScript, classes are templates for creating objects and are a part of its ES6 syntax. They don’t interact with the DOM's class attributes.

Here’s a quick example of JavaScript classes:

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

const dog = new Animal('Dog');
dog.speak(); // Output: Dog makes a noise.

JavaScript’s classList is for managing CSS classes, while JavaScript classes are for object-oriented programming.


Real-World Example: Toggle Active Classes

The classList.toggle() method can add or remove a class depending on its presence:

<div id="menu" class="hidden"></div>
<button id="toggleBtn">Toggle Menu</button>

<script>
  const menu = document.getElementById('menu');
  const toggleBtn = document.getElementById('toggleBtn');

  toggleBtn.addEventListener('click', () => {
    menu.classList.toggle('hidden');
  });
</script>

In this example, clicking the button toggles the hidden class on the menu.


Why Use classList?

Here’s why developers love classList:

  • Clean Syntax: No more messy string concatenations like with className.
  • Error-Free: Prevents accidentally overwriting existing classes.
  • Flexible: Offers methods like add(), remove(), toggle(), and contains().

A conclusion is here. ClassList is very important in DOM manipulation as it makes scripts cleaner and more maintainable. For creating dynamic UI elements or toggling class assignment states, utilizing classList is extremely useful! 

Now that you've learned about classList, try it out for yourself! Experiment with the different methods and see how you can use them to create dynamic and interactive web pages. And if you have any questions or cool examples to share, feel free to contact me.