JAVASCRIPT

Read and Update Custom Data Attributes

Explore how to effectively read and modify custom HTML `data-*` attributes using JavaScript's `dataset` property, enabling dynamic storage and retrieval of element-specific information.

function handleDataAttributes(elementId) {
  const element = document.getElementById(elementId);
  if (!element) {
    console.error('Element not found:', elementId);
    return;
  }

  console.log('--- Handling Data Attributes for:', element.tagName, element.id);

  // HTML example: <div id="myProduct" data-product-id="123" data-category="electronics">...</div>

  // Read a data attribute
  const productId = element.dataset.productId; // Accesses data-product-id
  const category = element.dataset.category;   // Accesses data-category
  console.log('Product ID:', productId);
  console.log('Category:', category);

  // Update a data attribute
  element.dataset.category = 'home-appliances';
  console.log('Updated category:', element.dataset.category);

  // Add a new data attribute
  element.dataset.price = '499.99';
  console.log('New price added:', element.dataset.price);

  // Remove a data attribute
  delete element.dataset.productId;
  console.log('Product ID after removal:', element.dataset.productId); // Will be undefined
}

// Example usage:
// <div id="myProduct" data-product-id="123" data-category="electronics">Product Info</div>
// handleDataAttributes('myProduct');
How it works: This snippet demonstrates how to interact with custom `data-*` attributes using the `dataset` property. It shows how to read existing data attributes (converting kebab-case in HTML to camelCase in JavaScript), update their values, add new data attributes, and even remove them. Data attributes are a versatile way to store extra, private information on standard HTML elements without violating HTML validity.

Need help integrating this into your project?

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

Hire DigitalCodeLabs