DEV Community

Beey
Beey

Posted on

The Classlist(CSS basics part 5/60)

Table Of Contents

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;";

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)