JAVASCRIPT

Read, Set, and Remove Custom Data Attributes

Learn to effectively manipulate custom `data-*` attributes on HTML elements using JavaScript, enabling dynamic content and interactive behavior.

// HTML Structure:
// <div id="myElement" data-status="active" data-user-id="12345">
//   This element has custom data.
// </div>
// <button id="updateDataBtn">Update Data</button>
// <button id="removeDataBtn">Remove User ID</button>

document.addEventListener('DOMContentLoaded', () => {
  const myElement = document.getElementById('myElement');
  const updateDataBtn = document.getElementById('updateDataBtn');
  const removeDataBtn = document.getElementById('removeDataBtn');

  // 1. Reading a data attribute
  const initialStatus = myElement.dataset.status; // Access via .dataset
  const initialUserId = myElement.dataset.userId; // CamelCase for hyphenated attributes
  console.log(`Initial Status: ${initialStatus}, User ID: ${initialUserId}`);

  // 2. Setting/Updating a data attribute
  updateDataBtn.addEventListener('click', () => {
    myElement.dataset.status = 'inactive'; // Set using .dataset
    myElement.dataset.lastUpdated = new Date().toLocaleTimeString(); // Add a new attribute
    console.log(`Updated Status: ${myElement.dataset.status}, Last Updated: ${myElement.dataset.lastUpdated}`);
  });

  // 3. Removing a data attribute
  removeDataBtn.addEventListener('click', () => {
    delete myElement.dataset.userId; // Remove using delete operator
    // or: myElement.removeAttribute('data-user-id');
    console.log('User ID data attribute removed.');
    console.log('Current User ID:', myElement.dataset.userId); // Will be undefined
  });
});
How it works: This snippet illustrates how to interact with custom `data-*` attributes on HTML elements using JavaScript. These attributes provide a way to store extra information about an element without requiring JavaScript state management. The `dataset` property of an element provides a convenient DOMStringMap interface to read, set, and remove these attributes. Hyphenated data attributes (e.g., `data-user-id`) are automatically camelCased (e.g., `element.dataset.userId`) for JavaScript access.

Need help integrating this into your project?

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

Hire DigitalCodeLabs