Table Of Contents

  • What is ClassList and why it is useful
  • Working out what you can do with classList
  • Common Mistakes

What is ClassList and why it is useful

As introduced in part 4, you may know that you can edit an object's CSS with javascript:

 const object = document.getElementById("object"); object.style = "color: red;"; 

The example is one method.

Another way which is considered better to use in some cases is by using classList.

Classlist can append, remove, and use conditional class removing instead of editing the style.

Example:

 const element = document.getElementById("MyElement"); element.classList.add("MyClass"); // Adds MyClass to the element 

Working out what you can do with classList

Another use of classList is classList.remove(ClassName)

It removes a specified class from the element if it exists on that element.

classList.toggle(ClassName) will remove the class if it's present and returns false, or it can add it if it's absent and returns true.

classList.contains(ClassName) returns a boolean if the class exists on the element.

classList.replace(OldClass, NewClass) swaps a class with a new one.

Common Mistakes

A common mistake with classList is forgetting to append the element variable to start for example: classList.add("MyClass") will throw an exception. MyElementVariable.classList.add("MyClass") works if your variable exists.