JAVASCRIPT
Get and Set Custom Data Attributes on DOM Elements
Learn to use JavaScript to easily access and modify custom `data-*` attributes, providing a flexible way to store and retrieve element-specific information directly in HTML.
// HTML: <div id="product" data-product-id="123" data-category="electronics">Product Info</div>
const productElement = document.getElementById('product');
// Get a data attribute value
const productId = productElement.dataset.productId; // '123' (camelCase for 'data-product-id')
const category = productElement.dataset.category; // 'electronics'
console.log('Product ID:', productId);
console.log('Category:', category);
// Set a data attribute value
productElement.dataset.price = '99.99'; // Adds data-price="99.99"
productElement.dataset.inStock = 'true'; // Adds data-in-stock="true"
// You can also use setAttribute and getAttribute for general attributes,
// but dataset is preferred for data-* attributes.
// productElement.setAttribute('data-color', 'red');
// const color = productElement.getAttribute('data-color'); // 'red'
console.log(productElement.outerHTML);
// Expected output (attributes might be in a different order):
// <div id="product" data-product-id="123" data-category="electronics" data-price="99.99" data-in-stock="true">Product Info</div>
How it works: Custom `data-*` attributes allow you to embed custom data directly into HTML elements, providing a useful way to store extra information without relying on non-standard attributes or global JavaScript variables. The `dataset` property (a `DOMStringMap`) provides a convenient way to access and modify these attributes in JavaScript, automatically converting between kebab-case HTML attributes and camelCase JavaScript properties for easy manipulation.