data-*
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
<object data="URL">
data-key
: The custom attribute name (must start withdata-
).value
: Thevalue
stored within the attribute.
Example
<!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 withdata-
and contain only lowercase letters). - A
value
(a string representing the stored data).
data-
unless explicitly used in scripts.Applies to
Since data-*
is a global attributes, it can be used with any HTML element.
Elements | Attribute |
---|---|
All HTML elements | data-* |
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.
crossorigin
The crossorigin attribute in HTML manages how browsers handle cross-origin requests for resources like images or scripts, affecting their privacy and security settings.
defer
The defer attribute in <script> tags delays script execution until after the document is fully parsed, improving loading time by preventing it from blocking page rendering.