JAVASCRIPT

Access and Modify Custom Data Attributes on DOM Elements

Understand how to read and update `data-*` attributes using JavaScript, enabling you to store extra information directly on HTML elements.

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

  // Read a data attribute
  const userId = element.dataset.userId; // For data-user-id
  const status = element.dataset.status; // For data-status
  console.log(`Element #${elementId} - User ID: ${userId}, Status: ${status}`);

  // Set/update a data attribute
  element.dataset.status = 'active'; // Sets data-status="active"
  element.dataset.lastUpdated = new Date().toISOString(); // Sets data-last-updated

  console.log(`Updated data-status to: ${element.dataset.status}`);
  console.log(`Added data-last-updated: ${element.dataset.lastUpdated}`);

  // Remove a data attribute
  delete element.dataset.status; // Removes data-status
  console.log(`data-status removed. Current status: ${element.dataset.status}`);
}

// Example Usage:
// <button id="myButton" data-user-id="123" data-status="pending">Click Me</button>
// manageDataAttributes('myButton');
How it works: HTML5 `data-*` attributes provide a way to store custom data private to the page or application directly within the DOM. This snippet shows how to easily access and modify these attributes using the `dataset` property of a DOM element. `dataset` converts hyphenated `data-` attributes (e.g., `data-user-id`) into camelCase JavaScript properties (e.g., `element.dataset.userId`), making them simple to work with.

Need help integrating this into your project?

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

Hire DigitalCodeLabs