JAVASCRIPT

Access and Modify HTML Custom Data Attributes

Learn how to effectively read and update custom data attributes (`data-*`) on DOM elements using JavaScript, allowing you to store and retrieve element-specific information.

function manageDataAttributes(elementId, dataKey, newValue) {
  const element = document.getElementById(elementId);

  if (!element) {
    console.error('Element not found:', elementId);
    return;
  }

  console.log(`--- Managing data-${dataKey} for #${elementId} ---`);

  // 1. Get existing data attribute value
  const currentValue = element.dataset[dataKey];
  console.log(`Current data-${dataKey}:`, currentValue);

  // 2. Set (or update) data attribute value
  if (newValue !== undefined) {
    element.dataset[dataKey] = newValue; // Using dataset API
    // Alternatively, for direct attribute manipulation:
    // element.setAttribute(`data-${dataKey}`, newValue);
    console.log(`Updated data-${dataKey} to:`, element.dataset[dataKey]);
  } else {
    console.log(`No new value provided for data-${dataKey}.`);
  }

  // 3. Remove data attribute (optional)
  // element.removeAttribute(`data-${dataKey}`);
  // console.log(`data-${dataKey} removed.`);

  // 4. Access all data attributes
  console.log('All data attributes:', element.dataset);
}

// Example Usage:
// HTML: <button id="myButton" data-id="123" data-state="active" data-action-type="submit">Click Me</button>

// Retrieve a data attribute
// manageDataAttributes('myButton', 'id'); // Shows "Current data-id: 123"

// Update a data attribute
// manageDataAttributes('myButton', 'state', 'inactive'); // Changes data-state to "inactive"

// Add a new data attribute
// manageDataAttributes('myButton', 'label', 'Save'); // Adds data-label="Save"
How it works: HTML custom data attributes (`data-*`) provide a way to store extra information about an element without requiring JavaScript variables or non-standard attributes. This snippet shows how to access and modify these attributes using the `dataset` property, which offers a convenient DOMStringMap interface. `element.dataset.myKey` automatically handles the conversion from `data-my-key` in HTML to `myKey` in JavaScript, making it easy to read and write values. This is incredibly useful for storing dynamic state, IDs, or other data directly on the DOM element for UI logic or integration with JavaScript frameworks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs