JS: List, Add, Remove Class Attribute

By Xah Lee. Date: . Last updated: .

Here is methods to list/add/remove a HTML/XML element's Class Attribute .

List Class Attributes

node.classList
Return the Class Attribute values as a Array-Like Object.

Add Class Attributes

node.classList.add(ClassName)
Adds a class value. If already exist, do nothing.

Remove Class Attributes

node.classList.remove(ClassName)
Removes a class value. No error if no exist.

Toggle Class Attributes

node.classList.toggle(ClassName)
Toggle a class value.
node.classList.toggle(ClassName, force)
force is true or false. If true, always add the class. Else, toggle.

Check Existance

node.classList.contains(ClassName)
Return true if node has the class value, else false.

Example

<div id="x48389" class="aaa bbb ccc"></div>
const xx = document.getElementById("x48389");

xx.classList;
xx.classList.add("hh");
xx.classList.remove("bbb");
xx.classList.contains("aaa");
xx.classList.toggle("aaa");

Basic DOM Element Methods