← Back to all snippets
JAVASCRIPT

Access and Manipulate HTML5 Data Attributes

Discover how to effectively use `dataset` to read and write custom HTML5 data attributes, enabling storage of small pieces of data directly on DOM elements.

<div id="dataItem" data-product-id="PROD123" data-user-status="active" style="border: 1px solid #c5cae9; padding: 10px; margin-top: 10px; background-color: #e8eaf6;">
  Product Information Display
</div>

<script>
const itemElement = document.getElementById('dataItem');

// --- Getting data attributes ---
const productId = itemElement.dataset.productId;     // Access 'data-product-id' as 'dataset.productId'
const userStatus = itemElement.dataset.userStatus; // Access 'data-user-status' as 'dataset.userStatus'

console.log(`Initial Product ID: ${productId}`);
console.log(`Initial User Status: ${userStatus}`);

// --- Setting/Modifying data attributes ---
itemElement.dataset.productId = 'PROD456'; // Update an existing data attribute
itemElement.dataset.newFeature = 'enabled'; // Add a new data attribute (becomes data-new-feature)

// You can also use setAttribute for compatibility or if you prefer
itemElement.setAttribute('data-admin-flag', 'true');

console.log(`Updated Product ID: ${itemElement.dataset.productId}`);
console.log(`New Feature Status: ${itemElement.dataset.newFeature}`);
console.log(`Admin Flag (via dataset): ${itemElement.dataset.adminFlag}`); // Note camelCase for get
console.log(`Admin Flag (via getAttribute): ${itemElement.getAttribute('data-admin-flag')}`);

// Removing a data attribute
delete itemElement.dataset.userStatus;
console.log('User status after deletion:', itemElement.dataset.userStatus); // Will be undefined
</script>
How it works: HTML5 `data-*` attributes provide a standard way to store custom, private data directly on HTML elements. The `dataset` property of an element returns a `DOMStringMap`, which offers a convenient API to access and manipulate these attributes. Attribute names like `data-product-id` are automatically camelCased to `dataset.productId` for JavaScript access. This snippet demonstrates how to read existing data attributes, update their values, add new ones, and even remove them. It's an excellent method for storing small, element-specific pieces of data without relying on global variables or complex JavaScript objects.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs