JAVASCRIPT

Get and Set Custom Data Attributes

Understand how to use the 'dataset' property to read and write custom data attributes ('data-*') on HTML elements, enabling client-side storage of small pieces of information.

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

if (productCard) {
  // Setting data attributes
  productCard.dataset.productId = 'SKU789';
  productCard.dataset.category = 'Footwear';
  productCard.dataset.discountPrice = '49.99'; // data-discount-price in HTML

  // Getting data attributes
  const productId = productCard.dataset.productId; // 'SKU789'
  const category = productCard.dataset.category;   // 'Footwear'
  const discountPrice = productCard.dataset.discountPrice; // '49.99'

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

  // Example of changing a data attribute
  productCard.dataset.category = 'Apparel';
  console.log('Updated Category:', productCard.dataset.category);
}
How it works: This snippet illustrates how to interact with HTML5 custom data attributes using the 'dataset' property. It shows how to both set new 'data-*' attributes programmatically and retrieve their values. Attributes with hyphens in HTML (e.g., 'data-discount-price') are accessed in JavaScript using camelCase ('dataset.discountPrice'), providing a convenient way to store and access small amounts of custom data directly on DOM elements.

Need help integrating this into your project?

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

Hire DigitalCodeLabs