The data-*
attribute in HTML is used to store custom data in HTML elements. It can be used to add information that can be easily accessed via JavaScript.
Using the data-*
attribute:
- Adding data to elements:
<div id="product" data-id="12345" data-name="Sample Product">Product</div>
- Accessing data via JavaScript:
const product = document.getElementById('product'); const productId = product.dataset.id; const productName = product.dataset.name; console.log(productId); // 12345 console.log(productName); // Sample Product
data-*
attributes are useful for storing additional data without the need for custom attributes or classes, allowing for better code organization and easier data access in scripts.