JAVASCRIPT

Read and Update Data Attributes

Explore how to access and modify custom `data-*` attributes on HTML elements using JavaScript's `dataset` API, perfect for storing and retrieving element-specific metadata.

function updateElementData(elementId, key, value) {
  const element = document.getElementById(elementId);
  if (element) {
    element.dataset[key] = value;
    console.log(`Data attribute 'data-${key}' updated to '${value}' on element '${elementId}'.`);
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
  }
}

function getElementData(elementId, key) {
  const element = document.getElementById(elementId);
  if (element) {
    const dataValue = element.dataset[key];
    console.log(`Data attribute 'data-${key}' for element '${elementId}':`, dataValue);
    return dataValue;
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
    return null;
  }
}

// Usage example:
// Assuming you have an element: <div id="productCard" data-id="123" data-price="29.99">Product A</div>

const productId = getElementData('productCard', 'id'); // Reads '123'
const productPrice = getElementData('productCard', 'price'); // Reads '29.99'

updateElementData('productCard', 'status', 'in-stock'); // Sets data-status="in-stock"
updateElementData('productCard', 'price', '24.99'); // Updates data-price="24.99"

console.log('Updated product status:', getElementData('productCard', 'status'));
console.log('Updated product price:', getElementData('productCard', 'price'));
How it works: HTML5 introduced custom `data-*` attributes, allowing developers to embed custom data directly into HTML elements. JavaScript's `dataset` property provides a convenient way to access and modify these attributes. This snippet shows how to retrieve data attributes using `element.dataset.propertyName` (camelCased from `data-property-name`) and how to update them, making it easy to store and manage element-specific metadata without relying on global JavaScript variables or complex data structures.

Need help integrating this into your project?

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

Hire DigitalCodeLabs