JAVASCRIPT
Read and Modify Data Attributes in JavaScript
Explore how to access and update custom data attributes (`data-*`) on HTML elements using JavaScript, enabling you to store and retrieve element-specific information.
document.addEventListener('DOMContentLoaded', () => {
const infoBox = document.getElementById('infoBox');
if (infoBox) {
// --- Reading Data Attributes ---
// Access using dataset property (camelCase)
const userId = infoBox.dataset.userId; // data-user-id becomes userId
const theme = infoBox.dataset.theme; // data-theme becomes theme
const isActive = infoBox.dataset.isActive === 'true'; // Convert string 'true'/'false' to boolean
console.log('User ID:', userId); // Output: 123
console.log('Theme:', theme); // Output: dark
console.log('Is Active:', isActive); // Output: true
// --- Modifying Data Attributes ---
// Set a new value
infoBox.dataset.theme = 'light';
console.log('Updated Theme:', infoBox.dataset.theme); // Output: light
// Add a new data attribute
infoBox.dataset.newSetting = 'enabled';
console.log('New Setting:', infoBox.dataset.newSetting); // Output: enabled
// Remove a data attribute
delete infoBox.dataset.newSetting;
console.log('New Setting after deletion:', infoBox.dataset.newSetting); // Output: undefined
}
});
/* Example HTML:
<div id="infoBox" data-user-id="123" data-theme="dark" data-is-active="true">User Information</div>
*/
How it works: HTML5 introduced custom data attributes (`data-*`) to store extra information about an element without requiring custom non-standard attributes or excessive DOM lookups. In JavaScript, these attributes are easily accessed and modified via the `element.dataset` property. Data attribute names with hyphens (e.g., `data-user-id`) are automatically converted to camelCase in JavaScript (e.g., `dataset.userId`). This provides a clean and semantic way to attach and manage small pieces of data directly on your DOM elements.