In JavaScript, you can remove a class from an element using the classList
property and its methods.
1. Using classList.remove()
method:
The classList
property of an element provides a remove()
method that can be used to remove a class from the element.
The syntax is as follows:
const element = document.getElementById("myElement");
element.classList.remove("myClass");
In the above example, the class named 'myClass'
will be removed from the element with the id
of 'myElement'
.
2. Using classList.toggle()
method:
The classList
property also provides a toggle()
method that can be used to add or remove a class from an element depending on its presence.
You can use it to remove a class as well by passing the class name as the first argument and false
as the second argument.
The syntax is as follows:
const element = document.getElementById("myElement");
element.classList.toggle("myClass", false);
In the above example, the class named 'myClass'
will be removed from the element with the id
of 'myElement'
.
3. Using className
method:
You can also remove a class from an element by manipulating the className
property of the element. You can replace the class name with an empty string to remove it. However, this approach is less recommended compared to using classList
methods as it does not provide the same flexibility and safety.
For example:
const element = document.getElementById("myElement");
element.className = element.className.replace("myClass", "");
In the above example, the class named 'myClass'
will be removed from the element with the id
of 'myElement'
.
Note:
It’s important to be careful when removing classes from elements, as it may affect the styling and behavior of the element on the page. Always ensure that you are removing the correct class from the correct element to avoid unintended consequences.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.