JAVASCRIPT

Dynamically Setting and Retrieving Data Attributes

Learn to dynamically set and retrieve HTML5 `data-*` attributes using JavaScript, enabling custom, non-visual data storage directly on DOM elements.

function setDataAttribute(elementSelector, dataKey, value) {
  const element = document.querySelector(elementSelector);
  if (element) {
    element.dataset[dataKey] = value;
    console.log(`Set data-${dataKey}='${value}' on ${elementSelector}`);
  } else {
    console.error('Element not found for data attribute setting:', elementSelector);
  }
}

function getDataAttribute(elementSelector, dataKey) {
  const element = document.querySelector(elementSelector);
  if (element) {
    const value = element.dataset[dataKey];
    console.log(`Retrieved data-${dataKey}='${value}' from ${elementSelector}`);
    return value;
  } else {
    console.error('Element not found for data attribute retrieval:', elementSelector);
    return null;
  }
}

// Example Usage:
// Assume an HTML element: <div id="product" data-id="P123" data-status="available">Product Details</div>

// Retrieve existing data attributes
// const productId = getDataAttribute('#product', 'id'); // 'P123'
// const productStatus = getDataAttribute('#product', 'status'); // 'available'

// // Set a new data attribute
// setDataAttribute('#product', 'category', 'Electronics');

// // Update an existing data attribute
// setDataAttribute('#product', 'status', 'out-of-stock');

// // Verify the updates
// console.log('Updated product category:', getDataAttribute('#product', 'category'));
// console.log('Updated product status:', getDataAttribute('#product', 'status'));
How it works: HTML5 `data-*` attributes provide a standard way to store custom data private to the page or application directly within the DOM. This snippet demonstrates how to dynamically set and retrieve these attributes using JavaScript. The `dataset` property on an element provides a convenient object-like interface to access `data-*` attributes. The `dataKey` (e.g., 'id' for `data-id`) is converted to camelCase (e.g., `element.dataset.id`). This pattern is incredibly useful for attaching metadata to elements that can be easily accessed and manipulated by JavaScript without relying on global variables or complex object mappings.

Need help integrating this into your project?

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

Hire DigitalCodeLabs