JavaScript: 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 .

node.classList
Return the Class Attribute values as a Array-Like Object.
node.classList.add(class_name)
Adds a class value. If already exist, do nothing.
node.classList.remove(class_name)
Removes a class value. No error if no exist.
node.classList.toggle(class_name)
Toggle a class value.
node.classList.toggle(class_name, force)
force is true or false. If true, always add the class. Else, toggle.
node.classList.contains(class_name)
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");
BUY
Ξ£JS
JavaScript in Depth

DOM Scripting

Overview

DOM Methods

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc