Manipulating CSS Class Properties Using JavaScript

Zoom

Zoom recording - starts at 00:21

Links

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.

Class Not Added
var createFirstClass = 
    document.getElementById("addClassOne");
createFirstClass.classList.add("classOne");
createFirstClass.textContent = 
    ".classOne added using .add()";
Class Not Added
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.

written with .classThree
var thirdClass = 
    document.getElementById("classThree");
thirdClass.classList.remove("classThree");
thirdClass.textContent = 
    ".classThree removed using .remove()";
written with .classFour

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".

Toggle .classOne & .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.

.classTwo and .classSix
var classSix = 
    document.getElementById("classSix");
classSix.className = "classFour";
classSix.textContent = 
    "overwritten by .classFour";

.replace

This returns the numbers of classes in the list.

.classFour replaces .classTwo
var classReplace = 
    document.getElementById("classReplace");
classReplace.classList.replace("classTwo", "classOne");