JAVASCRIPT
Working with Custom Data Attributes (dataset API)
Learn to store and retrieve custom data directly on HTML elements using the `dataset` API, a clean and powerful way for DOM-driven logic.
function manageDataAttribute(elementId, attributeName, value = null) {
const element = document.getElementById(elementId);
if (!element) {
console.warn(`Element with ID "${elementId}" not found.`);
return null;
}
// Set data attribute if value is provided
if (value !== null) {
element.dataset[attributeName] = value;
console.log(`Data attribute 'data-${attributeName}' set to '${value}' on element #${elementId}`);
}
// Always return the current value of the data attribute
return element.dataset[attributeName];
}
// Example Usage:
// Assume <div id="product-card" data-product-id="123" data-category="electronics">...</div>
// const productId = manageDataAttribute('product-card', 'productId');
// console.log('Current Product ID:', productId); // Output: 123
// manageDataAttribute('product-card', 'status', 'available');
// console.log('Updated Status:', manageDataAttribute('product-card', 'status')); // Output: available
How it works: This function demonstrates how to effectively get and set custom `data-*` attributes on HTML elements using the `dataset` API. By accessing `element.dataset`, you can manipulate attributes like `data-product-id` as `element.dataset.productId`. This provides a clean, standard, and separation-of-concerns approach to attach small pieces of data directly to DOM elements, useful for JavaScript behavior without cluttering class names or global variables. The function can both read existing data attributes and set new ones.