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 complete Javascript example to toggle class using JS
You can use classList.remove() method to remove a class
nameElem.classList.remove("anyclss")
You can also create Global function like this
function addClass( classname, element ) {
var cn = element.className;
//test for existance
if( cn.indexOf( classname ) != -1 ) {
return;
}
//add a space if the element already has class
if( cn != '' ) {
classname = ' '+classname;
}
element.className = cn+classname;
}
function removeClass( classname, element ) {
var cn = element.className;
var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
cn = cn.replace( rxp, '' );
element.className = cn;
}
so, basically it will help your to reuse same code again and again.
Hope it helps.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly