How to remove class names from an element with JavaScript
In this tutorial, we are going to learn about how to remove the class names from an HTML element with the help of JavaScript.
Removing a specific class name
To remove a specific class name from an element, we can use the classList.remove()
method by passing the class name as an argument.
Here is an example:
<p class="green box" id="text">Hello guru</p>
JavaScript:
const p = document.getElementById('text');
p.classList.remove('box');
In the example above, we only removed the box
class name from the p
element.
Removing all class names
We can also remove all class names from an element by setting its className
property to an empty string (''
).
Example:
<div class="container center red" id="left-div">
some text
</div>
JavaScript:
const div = document.getElementById('left-div');
div.className = ''; // it removes all class names from a div