How To Add Class In Javascript

In this blog post, we will discuss how to add a class to an HTML element using JavaScript. Modifying the class
attribute of an element allows you to apply different styles and manipulate the appearance of the page on the
fly. This can be useful for things like toggling styles or applying dynamic animations.

Adding Class Using the classList Property

The most common way to add a class in JavaScript is by using the classList property, which is
available on all HTMLElement objects. The classList property is an instance of the DOMTokenList
interface, which provides methods like add(), remove() and
toggle() to interact with the class attribute of an element.

To add a class, simply call the add() method on the classList property and pass the class name
as its argument. Here’s an example:

    const element = document.getElementById("my-element");
    element.classList.add("new-class");
    

Adding Multiple Classes at Once

You can also add multiple classes at once by passing them as separate arguments to the add()
method like this:

    const element = document.getElementById("my-element");
    element.classList.add("class-one", "class-two", "class-three");
    

Adding Class Using className Property

Another approach to add a class to an element is by using the className property. The
className property represents the class attribute of an element as a string. To add a class, you can simply
append the class name to the existing value of the className property:

    const element = document.getElementById("my-element");
    element.className += " new-class";
    

Note:

When using the className property, make sure to add a space before the class name to separate it from the
existing class names. Otherwise, the new class name will be merged with the existing class name.

Conclusion

In this blog post, we covered two popular methods for adding a class to an HTML element using JavaScript – the
classList and className properties. The classList property is generally the preferred approach due to its
simplicity and versatility. However, it’s good to know both methods as they can be useful in different
situations.