JAVASCRIPT
Access and Modify Custom Data Attributes
Learn how to read and update custom data attributes (`data-*`) on HTML elements using JavaScript's `dataset` property, useful for storing extra element-specific information.
function manageDataAttribute(elementId, key, value = null) {
const element = document.getElementById(elementId);
if (!element) {
console.error(`Element with ID '${elementId}' not found.`);
return null;
}
// Set the data attribute if a value is provided
if (value !== null) {
element.dataset[key] = value;
console.log(`Set data-${key} to '${value}' on #${elementId}.`);
return value;
}
// Otherwise, get and return the data attribute
else {
const dataValue = element.dataset[key];
console.log(`Retrieved data-${key} from #${elementId}: '${dataValue}'.`);
return dataValue;
}
}
// Example Usage:
// HTML structure: <div id="productCard" data-product-id="101" data-category="electronics">Product A</div>
// Get a data attribute
const productId = manageDataAttribute('productCard', 'productId');
console.log('Product ID:', productId); // Output: Product ID: 101
const category = manageDataAttribute('productCard', 'category');
console.log('Category:', category); // Output: Category: electronics
// Set (update) a data attribute
manageDataAttribute('productCard', 'category', 'home-appliances');
const updatedCategory = manageDataAttribute('productCard', 'category');
console.log('Updated Category:', updatedCategory); // Output: Updated Category: home-appliances
// Add a new data attribute
manageDataAttribute('productCard', 'price', '99.99');
const productPrice = manageDataAttribute('productCard', 'price');
console.log('Product Price:', productPrice); // Output: Product Price: 99.99
How it works: Custom data attributes (`data-*`) allow developers to embed custom data private to the page or application directly within the HTML. This snippet demonstrates how to interact with these attributes using JavaScript's `dataset` property. The `dataset` API provides a convenient way to access and modify `data-*` attributes via camelCase property names (e.g., `data-product-id` becomes `element.dataset.productId`). The provided function allows both retrieval and setting of these attributes, making it easy to store and manage element-specific data without relying on less semantic attributes or global JavaScript variables.