DOM: List/Add/Remove Class Attribute

By Xah Lee. Date: . Last updated: .

Here's methods to list/add/remove a HTML/XML element's class attribute.

elem.classList
Return elem's class attribute's space separated values as a Array-Like Object.
elem.classList.add(class_name)
Adds a class value to a element class attribute. If already exists, it will not add the class again.
elem.classList.remove(class_name)
Removes a class value to a element class attribute. No error if doesn't exist.
elem.classList.toggle(class_name)
Toggle a class value.
elem.classList.toggle(class_name, force)
force is true or false. If true, always add the class. Else, toggle.
elem.classList.contains(class_name)
Return true if elem contains 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");
βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


DOM

Overview

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc

jQuery

node.js