I wanted to add or remove classes from my HTML <div> dynamically using Javascript, I don't want to use jQuery here, so How can I add a class using JS?
If possible, I would also like to know how can I toggle class in Javascript
Suppose this is your HTML and you want to add a class using javascript
<div id="MainDiv" class="ClassForDiv">
</div>
So here is the Javascript for it to add class for <div id="div1">
var nameElem = document.getElementById("MainDiv");
nameElem.classList.add("anyclss");
Every element has a classList property containing its class attributes. This property provides methods that make it straightforward to add or remove a class.
function toggleClass() {
var myDivClasses = document.getElementById("MainDiv").classList;
if (myDivClasses.contains("blue")) {
myDivClasses.remove("blue");
}else {
myDivClasses.add("blue");
}
}
An even simpler way to accomplish the same thing is to use the toggle() method. Which will add the provided class if it is not present, or remove it if it is:
function toggleColor() {
document.getElementById("MainDiv").classList.toggle("blue");
}
here is the similar codepen example.
You can use classList.remove() method to remove a class
nameElem.classList.remove("anyclss")
Hope it helps.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly