JAVASCRIPT

Get and Set Custom Data Attributes on Elements

Understand how to store and retrieve custom data on HTML elements using `data-*` attributes and the `dataset` API, enabling more semantic and interactive web components.

document.addEventListener('DOMContentLoaded', () => {
  const userCard = document.getElementById('user-card');

  if (userCard) {
    // Get data attributes
    const userId = userCard.dataset.userId;
    const userName = userCard.dataset.userName;
    const isActive = userCard.dataset.isActive === 'true'; // Convert string to boolean

    console.log(`User ID: ${userId}, Name: ${userName}, Active: ${isActive}`);

    // Set/Update data attributes
    userCard.dataset.userRole = 'admin';
    userCard.dataset.lastLogin = new Date().toISOString();

    console.log('Updated user role:', userCard.dataset.userRole);
    console.log('Last login:', userCard.dataset.lastLogin);

    // Access using dot notation or bracket notation
    const city = userCard.dataset['userCity']; // Hyphenated attributes become camelCase
    console.log('User City:', city);
  }

  // Example of using data attributes for a click handler
  const actionButton = document.getElementById('action-button');
  if (actionButton) {
    actionButton.addEventListener('click', (event) => {
      const actionType = event.target.dataset.actionType;
      const actionId = event.target.dataset.actionId;
      console.log(`Button clicked with action: ${actionType}, ID: ${actionId}`);
      // Perform action based on data attributes
    });
  }
});
/* Example HTML structure: */
/*
<div id="user-card" data-user-id="123" data-user-name="Alice" data-is-active="true" data-user-city="New York">
  <h2>User Profile</h2>
  <p>Details about the user.</p>
</div>
<button id="action-button" data-action-type="edit" data-action-id="456">Edit Item</button>
*/
How it works: This snippet demonstrates how to interact with custom `data-*` attributes using the `dataset` property in JavaScript. It shows how to retrieve values (which are always strings) and how to set or update them dynamically. `dataset` provides a convenient and semantic way to store extra, non-standard information directly on HTML elements, which is highly useful for JavaScript to read and write for component logic without relying on IDs or classes for data storage.

Need help integrating this into your project?

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

Hire DigitalCodeLabs