JAVASCRIPT
Manage Custom Data Attributes on DOM Elements
Learn to store and retrieve non-standard, custom data directly on HTML elements using data attributes, enhancing interactivity and dynamic content without global variables.
// HTML structure might look like:
// <button id="myButton" data-action-type="delete" data-item-id="12345">Delete Item</button>
const myButton = document.getElementById('myButton');
// Setting a data attribute
myButton.dataset.isActive = 'true';
myButton.dataset.userId = 'user_abc';
// Getting a data attribute
const actionType = myButton.dataset.actionType; // 'delete'
const itemId = myButton.dataset.itemId; // '12345'
const isActive = myButton.dataset.isActive; // 'true'
console.log(`Action: ${actionType}, Item ID: ${itemId}, Is Active: ${isActive}`);
// Removing a data attribute
delete myButton.dataset.userId;
How it works: Custom data attributes (`data-*`) are a powerful feature for embedding custom data directly into HTML elements, providing a clean way to pass information from the HTML to JavaScript. This snippet demonstrates how to interact with them using the `dataset` property. You can set new data attributes by assigning values to `element.dataset.attributeName` (camelCased for JavaScript, hyphen-separated in HTML). Retrieving values is as simple as accessing `element.dataset.attributeName`. You can also remove attributes using the `delete` operator on the `dataset` property. This avoids polluting the global scope or using non-semantic attributes for data.