The HTML DOMTokenList Object: Managing Token Lists in HTML

The HTML DOMTokenList object provides a powerful way to manage lists of tokens, such as class names, within HTML elements. This object is crucial for dynamically manipulating CSS classes and other space-separated lists of strings in the DOM (Document Object Model). Understanding how to use the DOMTokenList effectively is essential for creating dynamic and interactive web applications. This guide will explore the DOMTokenList object in detail, covering its properties, methods, and real-world use cases.

What is the DOMTokenList Object?

The DOMTokenList object represents a collection of space-separated tokens in an HTML attribute, typically found in the class attribute of an element. It’s not an array but a list-like object that provides methods for adding, removing, toggling, and checking the presence of tokens. This allows for efficient and convenient manipulation of class names directly in JavaScript.

Purpose of the DOMTokenList Object

The primary purpose of the DOMTokenList object is to allow developers to:

  • Dynamically add, remove, and toggle CSS class names on HTML elements.
  • Check if a specific class name exists on an element.
  • Iterate over a list of class names.
  • Manipulate tokens in other space-separated attribute values, although class is its most common use.
  • Maintain clean and organized class structures.

Accessing a DOMTokenList

To access the DOMTokenList object for an element’s class attribute, use the classList property:

const element = document.getElementById("myElement");
const classList = element.classList;

Here, classList is the DOMTokenList object, and you can then use its methods to manipulate the class names.

Key DOMTokenList Properties

The DOMTokenList object has several important properties:

Property Type Description
`length` Number Returns the number of tokens (e.g., class names) in the list.
`value` String Returns the entire string of space-separated tokens as a single string.

Key DOMTokenList Methods

The DOMTokenList object provides several useful methods for manipulating token lists:

Method Description
`add(token1, token2, …)` Adds one or more tokens to the list. Duplicates are ignored.
`remove(token1, token2, …)` Removes one or more tokens from the list. Non-existing tokens are ignored.
`item(index)` Returns the token at the specified index. Returns `null` if the index is out of bounds.
`contains(token)` Returns `true` if the list contains the specified token; otherwise, returns `false`.
`replace(oldToken, newToken)` Replaces an existing token with a new token. Returns `true` if `oldToken` is replaced, otherwise `false`.
`toggle(token, force)` Toggles a token in the list. If the token is present, it’s removed. If absent, it’s added. If `force` is `true`, it always adds. If `force` is `false`, it always removes.
`entries()` Returns an iterator allowing to go through all key/value pairs contained in this object. (Keys are numbers starting from 0, and values are the tokens)
`keys()` Returns an iterator allowing to go through all keys of the key/value pairs contained in this object (Keys are numbers starting from 0)
`values()` Returns an iterator allowing to go through all values of the key/value pairs contained in this object (values are the tokens)
`forEach(callback, thisArg)` Executes a provided function once for each token in the `DOMTokenList`.

Basic Examples of DOMTokenList Usage

Let’s explore some basic examples using the DOMTokenList object.

Adding Class Names

Use the add() method to add one or more class names to an element.

<div id="elementAdd" class="initial-class">Initial Text</div>

<button id="addButton">Add Classes</button>

<script>


  const element_add = document.getElementById("elementAdd");
  const button_add = document.getElementById("addButton");
  button_add.addEventListener("click", () => {
    element_add.classList.add("new-class", "another-class");
        console.log(element_add.className);

  });


</script>
Initial Text

Note: The output may not visually change unless there is CSS attached to those classes. 🎨

Removing Class Names

Use the remove() method to remove one or more class names from an element.

<div id="elementRemove" class="class-to-remove another-class">Text</div>
<button id="removeButton">Remove Class</button>

<script>


  const element_remove = document.getElementById("elementRemove");
  const button_remove = document.getElementById("removeButton");
  button_remove.addEventListener("click", () => {
    element_remove.classList.remove("class-to-remove", "another-class");
    console.log(element_remove.className);
  });


</script>
Text

Checking for Class Names

Use the contains() method to check if an element has a specific class.

<div id="elementContains" class="my-class">Check Class</div>
<button id="containsButton">Check Class</button>
<p id="containsResult"></p>

<script>


  const element_contains = document.getElementById("elementContains");
  const button_contains = document.getElementById("containsButton");
  const result_contains = document.getElementById("containsResult");
  button_contains.addEventListener("click", () => {
    const hasClass = element_contains.classList.contains("my-class");
    result_contains.textContent = `Element has class "my-class": ${hasClass}`;
  });


</script>
Check Class

Toggling Class Names

Use the toggle() method to add or remove a class name based on its presence.

<div id="elementToggle" class="toggle-class">Toggle Me</div>
<button id="toggleButton">Toggle Class</button>

<script>


  const element_toggle = document.getElementById("elementToggle");
  const button_toggle = document.getElementById("toggleButton");
  button_toggle.addEventListener("click", () => {
    element_toggle.classList.toggle("toggle-class");
    console.log(element_toggle.className);
  });


</script>
Toggle Me

Replacing Class Names

Use replace() to replace a class with another class.

<div id="elementReplace" class="old-class">Replace Class</div>
<button id="replaceButton">Replace Class</button>

<script>


  const element_replace = document.getElementById("elementReplace");
  const button_replace = document.getElementById("replaceButton");
  button_replace.addEventListener("click", () => {
      element_replace.classList.replace("old-class", "new-class");
          console.log(element_replace.className);
  });


</script>
Replace Class

Advanced DOMTokenList Examples

Iterating Through Class Names

Use the forEach() method to loop through the class names:

<div id="elementIterate" class="class1 class2 class3">Iterate Classes</div>
<ul id="classListOutput"></ul>

<script>


  const element_iterate = document.getElementById("elementIterate");
    const output_list = document.getElementById('classListOutput')
  element_iterate.classList.forEach((className) => {
    const li = document.createElement('li');
    li.textContent = className;
    output_list.appendChild(li)
  });


</script>
Iterate Classes

    Using Iterators

    Use the entries(), keys(), and values() methods to iterate through the token list.

    <div id="elementIterator" class="token1 token2 token3">Token Iterators</div>
    
    <div id="iteratorOutput"></div>
    
    <script>
    
    
        const element_iterator = document.getElementById('elementIterator');
        const iterator_output = document.getElementById('iteratorOutput')
        let iteratorText = '<strong>Entries Iterator:</strong><br/>';
    
        for(const entry of element_iterator.classList.entries()){
            iteratorText += `Index: ${entry[0]}, Value: ${entry[1]} <br/>`;
        }
    
          iteratorText += '<br/><strong>Keys Iterator:</strong><br/>';
         for(const key of element_iterator.classList.keys()){
             iteratorText += `${key} <br/>`;
         }
        iteratorText += '<br/><strong>Values Iterator:</strong><br/>';
        for(const value of element_iterator.classList.values()){
             iteratorText += `${value} <br/>`;
        }
        iterator_output.innerHTML = iteratorText;
    
    
    </script>
    
    Token Iterators

    Real-World Applications

    The DOMTokenList object is used extensively in web development for:

    • Dynamic Styling: Changing an element’s appearance by adding or removing class names.
    • Interactive UI: Toggling UI elements (e.g., menus, modals) by adding or removing classes that control visibility.
    • State Management: Storing UI states as class names for persistence and manipulation.
    • Theme Switching: Dynamically changing the theme of a webpage by switching between different CSS class sets.
    • Accessibility: Adding or removing ARIA roles and properties to enhance the accessibility of interactive elements.

    Browser Support

    The DOMTokenList object enjoys excellent support across all modern web browsers, ensuring consistent behavior across different platforms.

    Note: While the DOMTokenList is widely supported, it’s always a good practice to test your code on different browsers to ensure compatibility. βœ…

    Conclusion

    The HTML DOMTokenList object is an indispensable tool for manipulating class names and other space-separated lists of tokens within HTML elements. Its intuitive methods and wide browser support make it a cornerstone of modern web development. By understanding and utilizing the DOMTokenList effectively, you can create more dynamic, interactive, and maintainable web applications. This comprehensive guide should provide you with the knowledge and examples you need to start leveraging the power of DOMTokenList in your projects.