In this article we will learn how to remove class from an element.
It is very common to remove class from an element in JavaScript.
Problem
Now we have a problem, which is that we want to remove a class to a specific element using JavaScript.
First we have to create a plain HTML file like this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- Added id to an element -->
<div id="element" class="one two three">
</div>
<!-- Your JavaScript File -->
<script src="main.js"></script>
</body>
</html>
As you can see, we created a file, created an element, and put ID on this element.
Now how will we remove the class on this element?
Well, the solution to this problem is simple, Using .classList.remove()
property.
This property is used to remove a class name to the selected element.
Syntax
element.classList.remove("YOUR_CLASS");
Remove class from an element using classList.remove()
We can use classList.remove()
to remove a class from an element.
Example
// Select element
const element = document.getElementById("element");
// Remove class
element.classList.remove("one");
// Result:
console.log(element);
Output
<div id="element" class="two three"></div>
As you can see we have removed class named one
from the element.
And if you want to remove more than one class, this is also easy.
// Select element
const element = document.getElementById("element");
// Remove classes
element.classList.remove("one", "two", "three");
// Result:
console.log(element);
Output
<div id="element" class=""></div>
Thank you for reading
Thank you for reading my blog. 🚀