data-*

HTML data attributes enable the storage of custom data on elements, accessible through JavaScript and prefixed with data-. This allows for attaching additional information without impacting the element's functionality.

data-* attributes

The data-* attributes are custom attributes that enable the exchange of proprietary information between HTML and the DOM. These attributes allow scripts to store and retrieve custom data efficiently.

Syntax

index.html
<object data="URL">
  • data-key: The custom attribute name (must start with data-).
  • value: The value stored within the attribute.

Example

::atter-data ::
index.html
<!DOCTYPE html>
<html>
<head>
  <script>
  function showDetails(animal) {
    let animalType = animal.getAttribute("data-animal-type");
    alert("The " + animal.innerHTML + " is a " + animalType + ".");
  }
  </script>
</head>
  <body>
    <h1>Species</h1>
    <p>Click on a species to see its type:</p>
    <ul>
      <li onclick="showDetails(this)" id="owl" data-animal-type="bird">Owl</li>
      <li onclick="showDetails(this)" id="salmon" data-animal-type="fish">Salmon</li>  
      <li onclick="showDetails(this)" id="tarantula" data-animal-type="spider">Tarantula</li>  
    </ul>
  </body>
</html>

Definition and Usage

The data-* attribute enables the storage of custom data in HTML elements. JavaScript can access this data to enhance user interactions. The attribute consists of:

  • A name (must start with data- and contain only lowercase letters).
  • A value (a string representing the stored data).
User agents ignore attributes prefixed with data- unless explicitly used in scripts.

Applies to

Since data-* is a global attributes, it can be used with any HTML element.

ElementsAttribute
All HTML elementsdata-*

See also

  • Global attributes.
  • The HTMLElement.dataset property, which allows accessing and modifying data attributes.
  • Using data attributes for dynamic content.

Conclusion

The data-* attribute is a powerful tool for storing custom data within HTML elements without affecting their structure or functionality. It enhances interactivity by allowing JavaScript to access and manipulate the stored information dynamically. Since it is a global attributes, it can be applied to any HTML element, making it highly versatile. By leveraging data-* attributes, developers can create more dynamic and user-friendly web applications while keeping their markup clean and semantic.