HTML Element classList Property: Dynamically Manage CSS Classes

The classList property in HTML DOM (Document Object Model) is a read-only property that returns a live DOMTokenList representing the class attribute of an element. It provides methods to add, remove, toggle, and check for the presence of CSS classes on an HTML element, making dynamic manipulation of CSS classes easy and efficient. This guide provides a detailed look at the classList property and its methods, complete with examples.

What is the classList Property?

The classList property is part of the HTML DOM API and allows JavaScript to interact with an element’s CSS classes. It is particularly useful for:

  • Dynamically changing the appearance of elements based on user interaction or application state.
  • Implementing interactive features that require adding or removing specific CSS classes.
  • Creating reusable components with configurable styles.

Syntax

The classList property is accessed on an HTML element object:

const elementClassList = element.classList;

Methods of classList

The classList property provides several methods to manipulate the CSS classes of an element:

Method Description
`add(className1, className2, …)` Adds one or more class names to the element’s class attribute. If the class already exists, it is not added again.
`remove(className1, className2, …)` Removes one or more class names from the element’s class attribute. If the class does not exist, the method does nothing.
`toggle(className, force)` Toggles the presence of a class name. If the class exists, it is removed and returns `false`; if it does not exist, it is added and returns `true`. The optional `force` parameter can be used to ensure the class is either added (`force` is `true`) or removed (`force` is `false`), regardless of its current state.
`contains(className)` Checks if the specified class name exists in the element’s class attribute. Returns `true` if the class exists, and `false` otherwise.
`item(index)` Returns the class name at the specified index in the list. Returns `null` if the index is out of range.
`replace(oldClass, newClass)` Replaces an existing class with a new class. If the old class doesn’t exist, it does nothing.
`entries()` Returns an `Iterator` allowing to go through all key/value pairs contained in the list.
`keys()` Returns an `Iterator` containing all keys in the list.
`values()` Returns an `Iterator` containing all values in the list.

Examples

Let’s explore some practical examples of using the classList property to dynamically manage CSS classes.

Adding a Class

This example demonstrates how to add a CSS class to an element using classList.add().

<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
</style>
</head>
<body>

<p id="myParagraph1">This is a paragraph.</p>

<button id="addClassButton1">Add Highlight Class</button>

<script>
  const paragraph1 = document.getElementById("myParagraph1");
  const addButton1 = document.getElementById("addClassButton1");

  addButton1.addEventListener("click", function() {
    paragraph1.classList.add("highlight");
  });
</script>

</body>
</html>

Output:

Clicking the “Add Highlight Class” button will apply the highlight class to the paragraph, changing its background color to yellow and making the text bold.

Removing a Class

This example shows how to remove a CSS class from an element using classList.remove().

<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
</style>
</head>
<body>

<p id="myParagraph2" class="highlight">This is a highlighted paragraph.</p>

<button id="removeClassButton2">Remove Highlight Class</button>

<script>
  const paragraph2 = document.getElementById("myParagraph2");
  const removeButton2 = document.getElementById("removeClassButton2");

  removeButton2.addEventListener("click", function() {
    paragraph2.classList.remove("highlight");
  });
</script>

</body>
</html>

Output:

Clicking the “Remove Highlight Class” button will remove the highlight class from the paragraph, reverting its style to the default.

Toggling a Class

This example demonstrates how to toggle a CSS class on an element using classList.toggle().

<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
</style>
</head>
<body>

<p id="myParagraph3">This is a paragraph.</p>

<button id="toggleClassButton3">Toggle Highlight Class</button>

<script>
  const paragraph3 = document.getElementById("myParagraph3");
  const toggleButton3 = document.getElementById("toggleClassButton3");

  toggleButton3.addEventListener("click", function() {
    paragraph3.classList.toggle("highlight");
  });
</script>

</body>
</html>

Output:

Clicking the “Toggle Highlight Class” button will add the highlight class to the paragraph if it’s not already present, or remove it if it is.

Checking for a Class

This example shows how to check if an element has a specific CSS class using classList.contains().

<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
</style>
</head>
<body>

<p id="myParagraph4" class="highlight">This is a paragraph.</p>

<button id="containsClassButton4">Check Highlight Class</button>

<script>
  const paragraph4 = document.getElementById("myParagraph4");
  const containsButton4 = document.getElementById("containsClassButton4");

  containsButton4.addEventListener("click", function() {
    const hasHighlight = paragraph4.classList.contains("highlight");
    alert("Paragraph has highlight class: " + hasHighlight);
  });
</script>

</body>
</html>

Output:

Clicking the “Check Highlight Class” button will display an alert indicating whether the paragraph has the highlight class.

Using item()

This example demonstrates how to access a class name at a specific index using classList.item().

<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
.anotherClass {
    color: blue;
}
</style>
</head>
<body>

<p id="myParagraph5" class="highlight anotherClass">This is a paragraph.</p>

<button id="itemClassButton5">Get Class at Index 0</button>

<script>
  const paragraph5 = document.getElementById("myParagraph5");
  const itemButton5 = document.getElementById("itemClassButton5");

  itemButton5.addEventListener("click", function() {
    const className = paragraph5.classList.item(0);
    alert("Class at index 0: " + className);
  });
</script>

</body>
</html>

Output:

Clicking the “Get Class at Index 0” button will display an alert showing the class name at index 0 (which is “highlight” in this case).

Replacing a Class

This example shows how to replace an existing class with a new class using classList.replace().

<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
.newClass {
    color: green;
}
</style>
</head>
<body>

<p id="myParagraph6" class="highlight">This is a paragraph.</p>

<button id="replaceClassButton6">Replace Highlight Class</button>

<script>
  const paragraph6 = document.getElementById("myParagraph6");
  const replaceButton6 = document.getElementById("replaceClassButton6");

  replaceButton6.addEventListener("click", function() {
    paragraph6.classList.replace("highlight", "newClass");
  });
</script>

</body>
</html>

Output:

Clicking the “Replace Highlight Class” button will replace the highlight class with the newClass on the paragraph, changing its style accordingly.

Real-World Applications of classList

The classList property is used in various scenarios, including:

  • Interactive Navigation Menus: Adding and removing classes to highlight the active menu item.
  • Form Validation: Adding classes to input fields to indicate validation status (e.g., error, success).
  • Dynamic Themes: Toggling classes on the body element to switch between light and dark themes.
  • Animation Control: Adding and removing classes to trigger CSS animations.

Browser Support

The classList property is supported by all modern browsers.

Note: For older browsers that do not support classList, you can use a polyfill or alternative methods like manipulating the className property directly, although this is generally less efficient and more cumbersome. 👴

Conclusion

The classList property is a powerful and convenient tool for dynamically managing CSS classes on HTML elements using JavaScript. By providing methods to add, remove, toggle, and check for the presence of classes, it simplifies the process of creating interactive and dynamic web applications. Understanding and utilizing the classList property can greatly enhance your ability to manipulate the styling and behavior of web elements in response to user interactions and application state.