classList

In this chapter you will learn:

  1. How to get and manage the class list for a HTML element

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

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

<!DOCTYPE HTML> <!--from j  av  a  2 s .c om-->
<html> 
<head> 
    <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

Next chapter...

What you will learn in the next chapter:

  1. How to get the class name for a HTML element
Home » Javascript Tutorial » HTML Operation
HTMLElement
addEventListener
appendChild
attributes
classList
className
cloneNode
createElement
createTextNode
dataset
getAttribute
getElementsByTagName
hasAttribute
innerHTML
insertAdjacentHTML
insertBefore
isSameNode
outerHTML
onmouseout
onmouseover
removeEventListener