JAVASCRIPT
Manage Custom Data Attributes with JavaScript
Learn to effectively retrieve and update custom data attributes (data-*) on HTML elements using the `dataset` API for storing element-specific data directly in the DOM.
function updateAndLogDataAttribute(elementId, key, value) {
const element = document.getElementById(elementId);
if (element) {
// Set a data attribute
element.dataset[key] = value;
console.log(`Data attribute 'data-${key}' set to: ${element.dataset[key]}`);
// Retrieve a data attribute
const retrievedValue = element.dataset[key];
console.log(`Retrieved 'data-${key}': ${retrievedValue}`);
// Note: data-my-key becomes element.dataset.myKey (camelCase)
} else {
console.error(`Element with ID '${elementId}' not found.`);
}
}
// Example Usage:
// Assume an HTML div: <div id="productCard" data-product-id="123" data-status="available"></div>
updateAndLogDataAttribute('productCard', 'status', 'out-of-stock');
updateAndLogDataAttribute('productCard', 'productId', '456'); // Accessing data-product-id
updateAndLogDataAttribute('productCard', 'newFeature', 'enabled'); // Adding a new data attribute
How it works: This snippet demonstrates how to interact with custom data attributes (`data-*`) using JavaScript's `dataset` API. Data attributes provide a standard way to store extra information about an HTML element without using non-standard attributes or the DOM. The `dataset` property of an element returns a `DOMStringMap` object, where each `data-name` attribute corresponds to a property `name` (converted to camelCase). This allows you to easily read and write data directly on elements, which is useful for JavaScript-driven UI components and state management.