JAVASCRIPT

Read and Write Custom Data Attributes

Effectively retrieve and update custom `data-*` attributes on HTML elements using JavaScript, enabling client-side storage of element-specific information.

<div id="productCard" data-product-id="789" data-category="electronics" data-in-stock="true">Product Details</div>

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

// Get data attributes using the dataset property (camelCase)
const productId = productCard.dataset.productId; // '789'
const category = productCard.dataset.category;   // 'electronics'
const inStock = productCard.dataset.inStock;     // 'true' (string!)

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

// Set or update data attributes
productCard.dataset.productId = '999';
productCard.dataset.price = '29.99';

// Data attributes are always strings, parse as needed
const newPrice = parseFloat(productCard.dataset.price); // 29.99

// You can also use getAttribute/setAttribute for direct access
const oldProductId = productCard.getAttribute('data-product-id');
productCard.setAttribute('data-new-custom-prop', 'some value');
</script>
How it works: HTML `data-*` attributes provide a standard way to embed custom data directly into HTML elements. JavaScript's `dataset` property offers a convenient `DOMStringMap` interface to access and modify these attributes using camelCase for property names (e.g., `data-product-id` becomes `dataset.productId`). All values retrieved from `dataset` are strings, so type conversion might be necessary. This allows developers to store and retrieve small pieces of element-specific data without relying on global variables or complex object structures.

Need help integrating this into your project?

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

Hire DigitalCodeLabs