Before HTML5, developers often had to use non-standard attributes or rely on classes and IDs in clumsy ways to store small pieces of data related to an element. HTML5 solved this problem with the data-* global attribute.
1. Defining the data-* Attribute
The data-* attribute allows you to embed custom data attributes on any HTML element.
- Format: The attribute name must start with the prefix
data-, followed by any string you choose (which should be descriptive). - Purpose: The data is intended for private use by the page’s scripts (JavaScript) or styles (CSS). Browsers do not render this data visually.
Example: Storing Product Information
In an e-commerce application, you might use data-* attributes to store the ID and price of a product element:
<button class="add-to-cart"
data-product-id="45873"
data-product-price="19.99">
Add to Cart
</button>
<div class="user-profile" data-user-status="premium">
Welcome, Alice!
</div>
2. Accessing Data with JavaScript
The true power of data-* attributes lies in the ease with which JavaScript can access and manipulate their values using the dataset property.
When accessing data-* via JavaScript:
- Find the element using an ID or class.
- Access the element’s
.datasetproperty. - The attribute name is converted from kebab-case (
data-product-id) to camelCase (productId).
Example: Retrieving the Product ID
Assuming the <button> element above has an id="cartButton":
<button id="cartButton" data-product-id="45873" data-product-price="19.99">
Add to Cart
</button>
// JavaScript Code
const button = document.getElementById('cartButton');
// Accessing the attribute: data-product-id becomes productId
const productId = button.dataset.productId; // Value: "45873"
// Accessing the attribute: data-product-price becomes productPrice
const productPrice = button.dataset.productPrice; // Value: "19.99"
console.log(`Adding item ${productId} for $${productPrice}`);
// Setting a new value
button.dataset.productId = "999";
console.log(`New ID: ${button.dataset.productId}`); // Output: New ID: 999
3. Styling with Data Attributes (CSS)
While typically used for JavaScript, you can use the attribute selector in CSS to style elements based on the value of their data-* attributes.
/* CSS Code */
/* Style a division only if the data-user-status is "premium" */
div[data-user-status="premium"] {
border: 2px solid gold;
background-color: #fffacd;
}
/* Style the button when its data-is-loading attribute is set to "true" */
button[data-is-loading="true"] {
opacity: 0.5;
cursor: wait;
}
In this scenario, JavaScript would simply toggle the value of data-is-loading between "true" and "false" to control the button’s visual state.
