CodeBlanks Logo Icon CodeBlanks

The classList API

JavaScript course · Intermediate · Lesson 27/134

Learn to add and remove classes with add, remove, toggle and contains.

What is classList?

Every HTML element has a property called classList. It is an easy way to manage the element's classes. With className you read and write the whole class list as one string; classList lets you add and remove single classes.

const box = document.querySelector('.box');
box.classList.add('active');

Here the 'active' class is added to the box element. If the class is already there, nothing happens.

toggle and contains

classList has two more useful methods. The toggle method adds the class if it is missing and removes it if it is present. The contains method returns true or false to report the class's presence.

box.classList.toggle('hidden');
if (box.classList.contains('hidden')) {
  // hidden
}

So you can hide and show an element on each button click; you do not need to check first.

Exercise Open the menu

The menu variable points to an element. To open the menu, first remove the 'closed' class, then add the 'open' class.

Show example solution
menu.classList.remove('closed');
menu.classList.add('open');

Test yourself

  1. Which adds the 'open' class?

    const box = document.querySelector('.box');
    // A
    box.classList.add('open');
    // B
    box.classList.remove('open');
    // C
    box.classList.toggle('open');
    // D
    box.classList.contains('open');
    • A
    • B
    • C
    • D
    Show answer

    A — Correct! add adds the class.

  2. Add a class

    const box = document.querySelector('.box');
    box.classList.____('highlight');
    Show answer
    const box = document.querySelector('.box');
    box.classList.add('highlight');
  3. Match classList methods

    add('x')
    Adds a class
    remove('x')
    Removes a class
    contains('x')
    Returns true/false

All lessons in Intermediate