JS: List, Add, Remove Class Attribute
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
orfalse
. Iftrue
, always add the class. Else, toggle.
Check Existance
node.classList.contains(ClassName)
-
Return
true
if node has the class value, elsefalse
.
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
- JS: What is Node, Node Type, Element
- JS: Get Element by ID, Name, Class etc
- JS: Get Element Parent, Child, Sibling
- DOM: NodeList vs HTMLCollection
- JS: Iterate HTMLCollection
- JS: Element Attribute Methods
- JS: List, Add, Remove Class Attribute
- JS: Create Element, Clone
- JS: Insert, Remove, Replace Element
- JS: Change Element Content
- JS: Add, Remove Event Handler