HTML className Property: Dynamically Manage Element Class Names

The HTML className property is a fundamental attribute for manipulating the class names of HTML elements using JavaScript. It allows you to dynamically add, remove, or toggle CSS classes, enabling powerful control over element styling and behavior based on user interactions, application state, or other dynamic conditions. This guide provides a comprehensive overview of the className property, including its syntax, usage, and practical examples.

What is the className Property?

The className property is a string representing the class attribute of an HTML element. It provides a direct way to access and modify the classes applied to an element via JavaScript. This is particularly useful for dynamically updating styles, triggering animations, or managing the visibility of elements in response to user actions.

Purpose of the className Property

The main purposes of the className property include:

  • Dynamically adding or removing CSS classes from an element.
  • Toggling CSS classes to switch between different styles or states.
  • Responding to user interactions by modifying element classes.
  • Controlling the appearance and behavior of elements based on application logic.

Syntax and Usage

The className property is accessed and modified directly through the DOM (Document Object Model) using JavaScript.

Accessing the className

To retrieve the current class name(s) of an HTML element, you can simply access the className property:

const element = document.getElementById("myElement");
const classNames = element.className;
console.log(classNames);

Modifying the className

To change the class name(s) of an HTML element, you can assign a new string to the className property:

const element = document.getElementById("myElement");
element.className = "newClass anotherClass";

Adding Classes

To add a class without overwriting existing classes, you can append the new class to the className string:

const element = document.getElementById("myElement");
element.className += " newClass";

Removing Classes

To remove a specific class, you can use string manipulation to replace the class name with an empty string:

const element = document.getElementById("myElement");
element.className = element.className.replace("oldClass", "");

Key Attributes and Methods

The className property itself doesn’t have attributes or methods in the traditional sense, but it’s essential to understand how it interacts with other DOM properties and methods.

| Property/Method | Description |
| :—————- | :————————————————————– |
| className | Gets or sets the value of the class attribute of an element. |
| classList | Provides a more convenient interface for adding, removing, and toggling classes. |
| element.id | Get direct access to element using id |
| document.querySelector() | Query the document to find any element |

Note: While className is widely supported, the classList property provides a more modern and convenient API for class manipulation. 👍

Examples

Let’s explore several examples demonstrating how to use the className property to dynamically manipulate CSS classes.

Basic Example: Adding a Class

This example demonstrates how to add a class to an element when a button is clicked.

<button id="addClassButton">Add Class</button>
<div id="myDiv" style="padding: 10px; border: 1px solid black;">
  This is a div.
</div>

<style>
  .highlight {
    background-color: yellow;
    font-weight: bold;
  }
</style>

<script>
  const addClassButton_ex1 = document.getElementById("addClassButton");
  const myDiv_ex1 = document.getElementById("myDiv");

  addClassButton_ex1.addEventListener("click", () => {
    myDiv_ex1.className += " highlight";
  });
</script>

Output:

Clicking the “Add Class” button will highlight the div with a yellow background and bold text.

Removing a Class

This example shows how to remove a class from an element when a button is clicked.

<button id="removeClassButton">Remove Class</button>
<div id="myDiv2" class="highlight" style="padding: 10px; border: 1px solid black;">
  This is a highlighted div.
</div>

<style>
  .highlight {
    background-color: yellow;
    font-weight: bold;
  }
</style>

<script>
  const removeClassButton_ex2 = document.getElementById("removeClassButton");
  const myDiv_ex2 = document.getElementById("myDiv2");

  removeClassButton_ex2.addEventListener("click", () => {
    myDiv_ex2.className = myDiv_ex2.className.replace("highlight", "");
  });
</script>

Output:

Clicking the “Remove Class” button will remove the highlight from the div.

Toggling a Class

This example demonstrates how to toggle a class on an element, adding it if it’s not present and removing it if it is.

<button id="toggleButton">Toggle Class</button>
<div id="myDiv3" style="padding: 10px; border: 1px solid black;">
  This is a div.
</div>

<style>
  .highlight {
    background-color: lightblue;
    font-style: italic;
  }
</style>

<script>
  const toggleButton_ex3 = document.getElementById("toggleButton");
  const myDiv_ex3 = document.getElementById("myDiv3");

  toggleButton_ex3.addEventListener("click", () => {
    if (myDiv_ex3.className.includes("highlight")) {
      myDiv_ex3.className = myDiv_ex3.className.replace("highlight", "").trim(); // trim to avoid leading/trailing spaces
    } else {
      myDiv_ex3.className += " highlight";
    }
  });
</script>

Output:

Clicking the “Toggle Class” button will toggle the highlight class on the div, changing its background color and font style.

Real-World Application: Dynamic Form Validation

Here’s a practical example of using the className property to provide dynamic form validation feedback.

<style>
  .valid {
    border: 2px solid green;
  }

  .invalid {
    border: 2px solid red;
  }
</style>

<input type="text" id="username" placeholder="Enter username" />
<p id="validationMessage"></p>

<script>
  const usernameInput_ex4 = document.getElementById("username");
  const validationMessage_ex4 = document.getElementById("validationMessage");

  usernameInput_ex4.addEventListener("input", () => {
    const username = usernameInput_ex4.value;
    if (username.length >= 5) {
      usernameInput_ex4.className = "valid";
      validationMessage_ex4.textContent = "Username is valid.";
      validationMessage_ex4.className = "valid";
    } else {
      usernameInput_ex4.className = "invalid";
      validationMessage_ex4.textContent = "Username must be at least 5 characters.";
      validationMessage_ex4.className = "invalid";
    }
  });
</script>

Output:

As the user types into the username input field, the input box will display a green border and a “Username is valid” message if the username is at least 5 characters long. Otherwise, it will display a red border and an “Username must be at least 5 characters” message.

Alternatives to className

While className is functional, the classList property offers a more convenient and modern API for class manipulation:

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

// Adding a class
element.classList.add("newClass");

// Removing a class
element.classList.remove("oldClass");

// Toggling a class
element.classList.toggle("active");

// Checking if a class exists
const hasClass = element.classList.contains("myClass");

The classList API provides methods for adding, removing, toggling, and checking the presence of classes, making it a more intuitive and readable alternative to direct string manipulation.

Browser Support

The className property is supported by all major browsers, ensuring broad compatibility across different platforms and devices.

Note: While className has excellent browser support, consider using classList for enhanced readability and functionality in modern browsers. 💡

Conclusion

The className property is a powerful tool for dynamically manipulating the class names of HTML elements, enabling flexible control over styling and behavior. By understanding its syntax, usage, and practical applications, you can create more interactive and responsive web applications. Whether you’re adding, removing, or toggling classes, the className property provides the means to dynamically update the appearance and functionality of your web pages.