HTML - Adding, Removing and Searching Classes with JavaScript
Adding new class to an HTML Element using JavaScript
// you can use any method, querySelector() etc
var ele = document.getElementById("elementId");
// replace className with your class name
ele.classList.add("className");
Removing a class from an HTML Element using JavaScript
// you can use any method, querySelector() etc
var ele = document.getElementById("elementId");
// replace className with your class name
ele.classList.remove("className");
Searching for a class in an HTML Element using JavaScript
// you can use any method, querySelector() etc
var ele = document.getElementById("elementId");
// replace className with your class name
if(ele.classList.remove("className")){
// finally, Found an element with some class
}
else{
// Element has no class
}
// you can use any method, querySelector() etc
var ele = document.getElementById("elementId");
// replace className with your class name
ele.classList.add("className");
// you can use any method, querySelector() etc
var ele = document.getElementById("elementId");
// replace className with your class name
ele.classList.remove("className");
// you can use any method, querySelector() etc
var ele = document.getElementById("elementId");
// replace className with your class name
if(ele.classList.remove("className")){
// finally, Found an element with some class
}
else{
// Element has no class
}
Using above methods, you can dynamically control an element's style , behavior etc
ALTERNATE TITLES