Change Element Class using JavaScript

Change Element Class using JavaScript

In this post, we will learn how we can toggle and change the class name from an HTML element using JavaScript.

To change any HTML element's class name we can use the classList.add() method or the classList.remove() method.

The classList object represents the content of the element's class attributes. And the classList.add() method helps to add a class to the element and the classList.remove() method lets us to remove the class from the HTML element.

Let's see how to add and remove a class from an element.

Suppose we have a <div> with id as "myDiv".

        <div id="myDiv">
            <p>This is a paragraph.</p>

Now to add a class to the element we can use this JavaScript code in the <script> tag.

const myDiv = document.getElementById("myDiv")

Now this will add the blue-bg class to the element.

Now to change or remove the background class we can write this code:

const myDiv = document.getElementById("myDiv")

Now this will remove the blue-bg class from the HTML element.

Now to change the element name dynamically we can write a function that will toggle the class on click of a button.

Let's first write the HTML code.

<div id="myDiv">
  <p>This is a paragraph.</p>
  <button onclick="toggleClass()">Toggle class</button>

It has a button with an onclick event to run the function toogleClass() .

Let's write the function in the script tags.

    function toggleClass(){
        const myDiv = document.getElementById("myDiv");

Here, we get the element by its id using getElementById() method.

The classLIst.toggle() method will add or remove the blue-bg class from the HTML element.

Conclusion: So to dynamically change element's class name, we can use the classList Javascript object properties like the add(), remove() and toggle() methods.