How to get and manage the class list for a HTML element in Javascript

Class list

classList property returns a DOMTokenList object.

DOMTokenList defines methods and properties that allow you to manage the class list.

MemberDescriptionReturns
add(class)Adds the specified class to the elementvoid
contains(class)Returns true if the element belongs to the specified classboolean
lengthReturns the number of classes to which the element belongsnumber
remove(class)Removes the specified class from the elementboid
toggle(class)Adds the class if it is not present and removes it if it is presentboolean

Example

The following code retrieves classes by index, using array-style notation.


<!DOCTYPE HTML> 
<html> 
<head> 
    <style> 
        p.newclass { <!-- w w w  .  j av a 2 s. c  o m-->
            background-color: grey; 
            color: white; 
        } 
    </style> 
</head> 
<body> 
    <p id="textblock" class="existing"> 
        this is a test.
    </p> 
    <pre id="results"></pre> 
    <button id="toggle">Toggle Class</button> 
    <script> 
    var results = document.getElementById("results"); 
    document.getElementById("toggle").onclick = toggleClass; 
    listClasses(); 
    function listClasses() { 
      var classlist = document.getElementById("textblock").classList; 
      results.innerHTML = "Current classes: " 
      for (var i = 0; i < classlist.length; i++) { 
          results.innerHTML += classlist[i] + " "; 
      } 
    } 
    function toggleClass() { 
      document.getElementById("textblock").classList.toggle("newclass"); 
      listClasses(); 
    } 
    </script> 
</body> 
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window