← Back to all snippets
JAVASCRIPT

Manage Custom Data Attributes with Element.dataset

Learn to store and access custom data directly on HTML elements using the `dataset` API, providing a clean, semantic way to bind application logic to the DOM without global variables.

const productCard = document.getElementById('productCard');

// Setting data attributes (becomes data-product-id, data-category in HTML)
productCard.dataset.productId = '12345';
productCard.dataset.category = 'electronics';
productCard.dataset.stockStatus = 'in-stock';

// Reading data attributes
const productId = productCard.dataset.productId;     // '12345'
const category = productCard.dataset.category;       // 'electronics'
const stockStatus = productCard.dataset.stockStatus; // 'in-stock'

console.log(`Product ID: ${productId}, Category: ${category}, Stock: ${stockStatus}`);

// Iterating through all data attributes
for (const key in productCard.dataset) {
  console.log(`data-${key}: ${productCard.dataset[key]}`);
}
How it works: The `dataset` property provides an interface to read and write all `data-*` custom data attributes on an element. It returns a `DOMStringMap`, which maps camel-cased property names (like `productId`) to their corresponding `data-` HTML attribute names (like `data-product-id`). This is an excellent way to store small bits of custom data related to an element directly in the HTML, allowing JavaScript to easily access and manipulate it without relying on `getAttribute` or `setAttribute` for each specific data attribute.

Need help integrating this into your project?

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

Hire DigitalCodeLabs