← Back to all snippets
JAVASCRIPT

Access and Manipulate Custom Data Attributes

Efficiently store and retrieve custom data within HTML elements using data attributes (`data-*`) and JavaScript's `dataset` API for dynamic application logic.

const itemCard = document.getElementById('product-card-123');

if (itemCard) {
  // Assuming HTML: <div id="product-card-123" data-product-id="456" data-status="available" data-price="19.99">...</div>

  // Accessing data attributes using dataset (camelCase for multi-word attributes)
  console.log('Product ID:', itemCard.dataset.productId);
  console.log('Product Status:', itemCard.dataset.status);

  // Modifying a data attribute
  itemCard.dataset.status = 'sold-out';
  console.log('Updated Status:', itemCard.dataset.status);

  // Adding a new data attribute
  itemCard.dataset.discount = '10%';
  console.log('Discount added:', itemCard.dataset.discount);
}
How it works: This snippet demonstrates the use of the `dataset` property to easily access and modify custom data attributes (those prefixed with `data-`) directly on HTML elements. Data attributes provide a clean and standardized way to embed small pieces of custom data into the DOM, which can then be read and manipulated by JavaScript without relying on non-standard attributes or complex parsing. Note that `data-product-id` in HTML becomes `dataset.productId` in JavaScript (camelCase conversion).

Need help integrating this into your project?

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

Hire DigitalCodeLabs