JAVASCRIPT

Work with Custom Data Attributes (data-*)

Store and retrieve custom data directly on HTML elements using `data-*` attributes and JavaScript's `dataset` API. Enhance interactivity and manage dynamic content efficiently.

const myElement = document.getElementById('dataElement');

if (myElement) {
  // Setting a data attribute
  myElement.dataset.userId = '12345';
  myElement.dataset.productName = 'AwesomeGadget';
  myElement.dataset.isActive = true; // Stored as string "true"

  // Getting data attributes
  const userId = myElement.dataset.userId; // "12345"
  const productName = myElement.dataset.productName; // "AwesomeGadget"
  const isActive = myElement.dataset.isActive; // "true"

  console.log('User ID:', userId);
  console.log('Product Name:', productName);
  console.log('Is Active:', isActive);

  // Accessing attributes directly (less convenient for data-*)
  const dataUserId = myElement.getAttribute('data-user-id'); // "12345"
  console.log('User ID (getAttribute):', dataUserId);

  // Example: change text based on data attribute
  if (myElement.dataset.isActive === 'true') {
    myElement.textContent = `User ${userId} is currently active.`;
  }
}
How it works: HTML `data-*` attributes provide a way to store custom data private to the page or application directly in the HTML. JavaScript's `dataset` API offers a convenient way to access and manipulate these attributes. `element.dataset.keyName` automatically converts `data-key-name` into camelCase, simplifying data retrieval and modification for dynamic UI behavior without relying on global variables.

Need help integrating this into your project?

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

Hire DigitalCodeLabs