JAVASCRIPT
Set and Retrieve Custom Data Attributes on DOM Elements
Learn to store and access custom data directly on HTML elements using `data-*` attributes and JavaScript's `dataset` API, perfect for managing UI state and element-specific logic.
function manageElementData(elementId, key, value = null) {
const element = document.getElementById(elementId);
if (!element) {
console.error(`Element with ID '${elementId}' not found.`);
return null;
}
if (value !== null) {
// Set a data attribute
element.dataset[key] = value;
console.log(`Data attribute 'data-${key}' set to '${value}' on #${elementId}.`);
} else {
// Retrieve a data attribute
const retrievedValue = element.dataset[key];
console.log(`Retrieved 'data-${key}' from #${elementId}: '${retrievedValue}'.`);
return retrievedValue;
}
}
// Example usage:
// In your HTML: <button id="productBtn" data-product-id="123" data-category="electronics">View Product</button>
// Set new data: manageElementData('productBtn', 'price', '499.99');
// Retrieve existing: const productId = manageElementData('productBtn', 'productId'); // '123'
// Retrieve new: const productPrice = manageElementData('productBtn', 'price'); // '499.99'
How it works: HTML `data-*` attributes allow you to embed custom data directly into HTML elements, making them a great way to store small pieces of information related to the element's state or functionality. JavaScript provides the `dataset` property on elements, which offers a convenient way to access and manipulate these attributes. This snippet shows how to both set new `data-*` attributes (using camelCase for JavaScript property names) and retrieve their values, providing a clean separation of concerns for your markup and logic.