JAVASCRIPT
Interact with Custom Data Attributes
Learn to effectively use HTML `data-*` attributes for storing custom data on elements and access or modify them via JavaScript for dynamic behavior.
const itemCard = document.getElementById('productCard');
// Set a data attribute
itemCard.dataset.productId = 'p-456-abc'; // Equivalent to setAttribute('data-product-id', 'p-456-abc')
itemCard.dataset.category = 'electronics'; // Automatically camelCases 'data-category'
// Get a data attribute
const productId = itemCard.dataset.productId;
const category = itemCard.dataset.category;
console.log('Product ID:', productId);
console.log('Category:', category);
// Check if a data attribute exists and set if not
if (itemCard.dataset.hasImage === undefined) {
itemCard.dataset.hasImage = 'true';
}
// Remove a data attribute
delete itemCard.dataset.category; // Equivalent to removeAttribute('data-category')
// Example HTML setup (not part of snippet, but for context):
// <div id="productCard" data-stock-count="15" data-category="books">Product Name</div>
How it works: This snippet shows how to work with HTML `data-*` attributes using JavaScript's `dataset` property. `dataset` provides a convenient way to access and modify custom data attributes. When accessing, attributes like `data-product-id` are automatically camelCased to `productId`. You can assign new values, retrieve existing ones, or delete them, making `data-*` attributes powerful for storing element-specific information without relying on non-standard attributes. This is a clean way to pass data from HTML to JavaScript.