JAVASCRIPT

Reading and Modifying Custom Data Attributes

Learn how to effectively access and manipulate custom `data-*` attributes on HTML elements using JavaScript. Store and retrieve element-specific data directly in the DOM for enhanced interactivity.

const handleDataAttributes = (selector, dataKey, value) => {
  const element = document.querySelector(selector);
  if (!element) {
    console.error('Element not found.');
    return null;
  }

  // Convert dataKey to camelCase for dataset API if not already
  const camelCaseKey = dataKey.replace(/-([a-z])/g, (g) => g[1].toUpperCase());

  if (value === undefined) {
    // Get data attribute
    return element.dataset[camelCaseKey];
  } else {
    // Set data attribute
    element.dataset[camelCaseKey] = value;
    return value;
  }
};

// Usage example:
// <button id="myButton" data-user-id="123" data-action="edit">Edit User</button>

// Get a data attribute:
// const userId = handleDataAttributes('#myButton', 'user-id');
// console.log(userId); // "123"

// Set a data attribute:
// handleDataAttributes('#myButton', 'action', 'delete');
// console.log(document.querySelector('#myButton').dataset.action); // "delete"

// You can also directly access:
// const directUserId = document.querySelector('#myButton').dataset.userId;
How it works: Custom `data-*` attributes provide a way to store extra information on standard HTML elements. This snippet demonstrates how to read and write these attributes using the `dataset` API in JavaScript. It automatically handles the conversion between hyphen-separated HTML attribute names and camelCase JavaScript property names, making it convenient for passing dynamic data between HTML and JavaScript logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs