Custom Data Attributes (data-*
)
Custom data attributes provide a way to store extra information on standard HTML elements without using non-standard attributes or the DOM. This allows you to embed custom data private to the page or application directly within the HTML.
Example 1: data-id
for unique identification
<button data-id="product-123" class="add-to-cart">Add to Cart</button>
Explanation The data-id
attribute stores a unique identifier for the product associated with the button. JavaScript can then easily access this ID to perform actions like adding the correct item to a shopping cart.
Example 2: data-category
for filtering
<li data-category="electronics">Laptop</li>
Explanation The data-category
attribute helps categorize elements on a webpage. This is incredibly useful for filtering, sorting, or styling specific groups of content using JavaScript or CSS.
Example 3: data-status
for dynamic state
<div data-status="pending">Order #456</div>
Explanation The data-status
attribute allows you to store the current state of an element, such as "pending," "completed," or "failed." This is excellent for updating UI based on application logic without heavy DOM manipulation.
Example 4: data-price
for product information
<span data-price="99.99">Price: $99.99</span>
Explanation Using data-price
lets you embed specific numeric data directly into the HTML. This data can then be easily accessed by JavaScript for calculations, such as summing up total costs in a shopping cart.
Example 5: data-tooltip
for dynamic tooltips
<img src="info.png" alt="Information" data-tooltip="More details here">
Explanation The data-tooltip
attribute stores text that can be used to generate dynamic tooltips when a user hovers over the element. This enhances user experience by providing contextual information on demand.