classList

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

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

 
<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
        <style> 
            p.newclass { 
                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 Book 
    DOM  

HTMLElement:
  1. The HTMLElement Members
  2. element tag name, id, direction, language, hidden disabled information
  3. addEventListener
  4. appendChild
  5. attributes returns a collection containing all of the attributes
  6. classList
  7. className
  8. cloneNode
  9. createElement
  10. createTextNode
  11. dataset
  12. getAttribute
  13. getElementsByTagName
  14. hasAttribute
  15. innerHTML
  16. insertAdjacentHTML
  17. insertBefore
  18. isSameNode
  19. outerHTML
  20. onmouseout
  21. onmouseover
  22. querySelectorAll
  23. removeEventListener