JAVASCRIPT
Get and Set Custom Data Attributes on a DOM Element
Efficiently retrieve and update custom data attributes (data-*) on any HTML element in the DOM using JavaScript's dataset property for dynamic behavior.
function manageDataAttributes(elementId, key, value = null) {
const element = document.getElementById(elementId);
if (!element) {
console.error('Element not found:', elementId);
return null;
}
if (value !== null) {
// Set a data attribute
element.dataset[key] = value;
console.log(`Data attribute 'data-${key}' set to '${value}' for element '${elementId}'.`);
} else {
// Get a data attribute
const dataValue = element.dataset[key];
console.log(`Data attribute 'data-${key}' for element '${elementId}': '${dataValue}'.`);
return dataValue;
}
}
// Example Usage:
// Assume you have an HTML element like: <button id="myButton" data-action="click" data-status="active">Click Me</button>
// Get a data attribute
manageDataAttributes('myButton', 'action'); // Outputs: Data attribute 'data-action' for element 'myButton': 'click'.
// Set a new data attribute
manageDataAttributes('myButton', 'status', 'inactive'); // Outputs: Data attribute 'data-status' set to 'inactive' for element 'myButton'.
// Get the updated data attribute
manageDataAttributes('myButton', 'status'); // Outputs: Data attribute 'data-status' for element 'myButton': 'inactive'.
How it works: This code snippet illustrates how to interact with HTML5 custom data attributes (prefixed with `data-`) using JavaScript. The `dataset` property on a DOM element provides a convenient way to access these attributes as properties of an object. This function allows you to either retrieve the value of an existing data attribute or set a new value for a specified key, making it useful for storing and manipulating small pieces of data directly on elements.