Javascript add or remove class to a given element

Today in this tutorial we learn how to add or remove a class from an element. More then times we need to add an extra class name to a existing div and javascripti or jquery is best way to adding new class in a div element.

Here we are going to share a easy example to add class to a div using javascript. We get the element using id and then add class using `classList` predefined events of javascript. If you are search Javascript Check If Element Contains Class Name Example then we already expalin in previous tutorial.

Let’s see to add or remove element class in javascript easiest way to do this without any framework is to use element.classList.add method.

Adding class:

First we get the div element using getElementById where we want to add the class name. Then we add the class name using classList javascript method just like below.

const element= document.getElementById('testId');
element.classList.add("test-class");

Removing Class:

If you are remove class from a div element then you need to something like below code.

const element= document.getElementById('testId');
element.classList.remove("test-class");

Add Class to a Given Element Javascript Example Code

Here the the full example to add class in a div using javascript.

<body>
<div id="testId">
    This is a DIV element.
</div>

<button onclick="addClass()">Try it</button>

<script>
    function addClass() {
       const element = document.getElementById("testId");
       element.classList.add("test-class");
    }
</script>
</body>

If you need to support Internet Explorer 9 or lower:

If your browser is Internet Exmlorer 9 or lower version then you can add the below code for adding class to a div.

<body>
<div id="testId" class="someclass">
    This is a DIV element.
</div>
<button onclick="addClass()">Try it</button>

<script>
    function addClass() {
       let element = document.getElementById("testId");
       element.className += " otherclass";
    }
</script>
</body>

Note: For this example the space before otherclass. It’s important to include the space otherwise it compromises existing classes that come before it in the class list.

Hope the following best example help for adding class to a given element using javascript. For more follow us on social networks.

1 thought on “Javascript add or remove class to a given element”

Leave a Comment