JavaScript Code


How to remove a classname for a div using JavaScript?


Tutorials using JS

Remove a classname for a div using JavaScript

In this tutorial, you shall learn how to remove a classname from existing classnames of a div element using JavaScript.

Solution

To remove a classname from the existing classnames of a div element using JavaScript, we can use Element.classList property. Call remove() method on the classList property and pass the required classname as argument.

divElement.classList.remove('dark');

Program

When user clicks on the Click me button, we get the div element with the id myDiv, and remove the classname tile from the existing classnames using Element.classList.remove().

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Remove classname for a div</h2>
<button id="myBtn">Click me</button>
<div id="myDiv" class="card tile active">About</div><br>
<pre id="output"></pre>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
    //get div element
    const myDiv = document.getElementById("myDiv");
    //remove classname of div
    myDiv.classList.remove("tile");
    document.getElementById("output").innerHTML = myDiv.classList;
});
</script>

</body>
</html>


Copyright @2022