In this tutorial, we will see the different methods for To Add and Remove CSS Class Using Javascript by taking the reference of the element ID.
Add or Appending CSS Class Using Javascript
There are two possible ways to add or append the CSS class to the HTML element i.e via className
and classList
CSS Class Using Javascript className
method
It contains all the class name in a string format, to add or append class we have to use the string addition technique.
For adding single class name to element.
var el = document.getElementById('#foo');
el.className = 'my-class';
For Appending single class name to element.
var el = document.getElementById('#foo');
el.className += ' my-another-class';
// OR
el.className = el.className + " my-another-class";
CSS Class Using Javascript classList
method
The classList
is sweet and simple to use as it contains the list of the class name in an array of string format.
classList
comes up with four possible methods linked to it.
add
– Adds a class to an element’s list of classes. If class already exists in the element’s list of classes, it will not add the class again.remove
– Removes a class from an element’s list of classes. If class does not exist in the element’s list of classes, it will not throw an error or exception.toggle
– Toggles the existence of a class in an element’s list of classescontains
– Checks if an element’s list of classes contains a specific class
var el = document.getElementById("div1");
// Adding Single class
el.classList.add("my-class");
// Adding Multiple calsses
el.classList.add("my-class", "my-another-class");
var el = document.getElementById("divID");
// Removing class
el.classList.remove("my-class");
var el = document.getElementById("divID");
// If active is set remove it, otherwise add it
el.classList.toggle("active");
var el = document.getElementById("divID");
if (el.classList.contains("my-class")) {
// Has my-class in it
} else {
// dont Have my-class
}
Browser Support
classList
is only supporter in IE10 and later, also Opera Mini seems not to support it. See support table at caniuse.com
Polyfill
Repo that makes classList work in IE8 and IE9.