JAVASCRIPT
Storing and Accessing Custom Data with HTML `dataset`
Discover how to embed and retrieve custom data directly within HTML elements using `data-*` attributes and JavaScript's `dataset` API for dynamic interactions without extra JavaScript variables.
// HTML Structure example:
// <button id="buyButton" data-product-id="123" data-product-name="Super Widget" data-price="29.99">
// Add to Cart
// </button>
document.getElementById('buyButton').addEventListener('click', function(event) {
const button = event.target;
const productId = button.dataset.productId; // Accesses data-product-id
const productName = button.dataset.productName; // Accesses data-product-name
const price = parseFloat(button.dataset.price); // Accesses data-price
console.log(`Adding ${productName} (ID: ${productId}, Price: $${price}) to cart.`);
// You can also set data attributes programmatically
button.dataset.status = 'processing';
console.log('Button status:', button.dataset.status);
});
How it works: The `dataset` property provides an easy way to access custom `data-*` attributes set on HTML elements. These attributes are useful for storing small pieces of custom data directly in the HTML, making it accessible via JavaScript. When accessing `data-product-id`, JavaScript automatically converts it to `dataset.productId` (camelCase). You can also dynamically update these attributes, providing a flexible way to manage element-specific state.