Zoom
Zoom recording - starts at 00:21Links
Adding a Class
There are two ways to add a new class to an element. The first is classList.add("newClass")
and the second is classList += "newClass"
. Multiple classes can be added by
placing a , and an empty space between class names.
var createFirstClass =
document.getElementById("addClassOne");
createFirstClass.classList.add("classOne");
createFirstClass.textContent =
".classOne added using .add()";
var createSecondClass =
document.getElementById("addClassTwo");
createSecondClass.classList += "classTwo";
createSecondClass.textContent =
".classTwo added using +=";
Removing a Class
There are two ways to remove a class from an element. The first is classList.remove("newClass")
and the second is classList -= "newClass"
. Multiple classes can be removed
by placing a , and an empty space between class names.
var thirdClass =
document.getElementById("classThree");
thirdClass.classList.remove("classThree");
thirdClass.textContent =
".classThree removed using .remove()";
classList.contains
The .contains
manipulation returns a boolean value. You can check to see if an element contains a particular class. For example, does #classContains
have an attribute of /classTwo
?
classList.toggle
You can toggle between two classes or adding one by using classList.toggle("classToToggle")
. The example below has "classOne" assigned to it and toggles "classFour".
var classFive =
document.getElementById("toggleClass");
classFive.classList.toggle("classFive");
className
Using className
will overwrite any existing classes and create a new one if it doesn't exist. It is better to use other add options to create class names, though.
var classSix =
document.getElementById("classSix");
classSix.className = "classFour";
classSix.textContent =
"overwritten by .classFour";
.replace
This returns the numbers of classes in the list.
var classReplace =
document.getElementById("classReplace");
classReplace.classList.replace("classTwo", "classOne");