JAVASCRIPT
Manage Custom Data Attributes with JavaScript `dataset` API
Understand how to store and retrieve custom data on HTML elements using the `data-*` attributes and JavaScript's `dataset` property, enabling dynamic element behavior.
function updateElementData(elementId, key, value) {
const element = document.getElementById(elementId);
if (element) {
element.dataset[key] = value;
console.log(`Set data-${key}='${value}' on element ID '${elementId}'.`);
} else {
console.warn(`Element with ID '${elementId}' not found.`);
}
}
function getElementData(elementId, key) {
const element = document.getElementById(elementId);
if (element) {
const value = element.dataset[key];
console.log(`Got data-${key}='${value}' from element ID '${elementId}'.`);
return value;
} else {
console.warn(`Element with ID '${elementId}' not found.`);
return null;
}
}
// Example Usage:
// HTML: <button id="myButton" data-action="delete" data-itemId="123"></button>
// updateElementData('myButton', 'status', 'pending');
// console.log(getElementData('myButton', 'action')); // Output: "delete"
// console.log(getElementData('myButton', 'itemId')); // Output: "123"
// console.log(getElementData('myButton', 'status')); // Output: "pending"
How it works: This snippet demonstrates how to interact with custom `data-*` attributes using the `dataset` property of HTML elements. `updateElementData` allows you to set or modify a `data-*` attribute, where `key` is converted to kebab-case (e.g., `itemId` becomes `data-item-id`). `getElementData` retrieves the value of a specified `data-*` attribute. This is invaluable for storing small pieces of application-specific state directly on DOM elements without relying on global variables.