JAVASCRIPT

Manage Custom Data Attributes with dataset

Explore how to store and retrieve custom data on HTML elements using JavaScript's `dataset` property for enhanced interactivity and state management.

function manageElementData(elementId, action, key, value) {
  const element = document.getElementById(elementId);
  if (!element) {
    console.error(`Element with ID '${elementId}' not found.`);
    return null;
  }

  switch (action) {
    case 'set':
      element.dataset[key] = value;
      console.log(`Data attribute 'data-${key}' set to '${value}' on '${elementId}'.`);
      return true;
    case 'get':
      const dataValue = element.dataset[key];
      console.log(`Data attribute 'data-${key}' on '${elementId}' is: '${dataValue}'.`);
      return dataValue;
    case 'remove':
      delete element.dataset[key];
      console.log(`Data attribute 'data-${key}' removed from '${elementId}'.`);
      return true;
    case 'getAll':
      console.log(`All data attributes on '${elementId}':`, element.dataset);
      return { ...element.dataset }; // Return a copy
    default:
      console.error(`Unknown action: '${action}'. Use 'set', 'get', 'remove', or 'getAll'.`);
      return null;
  }
}

// Example usage:
// Assume you have an HTML element: <button id="myButton" data-status="active" data-user-id="123">Click Me</button>

// Get a data attribute:
const status = manageElementData('myButton', 'get', 'status'); // 'active'
const userId = manageElementData('myButton', 'get', 'userId'); // '123' (note camelCase in JS)

// Set a data attribute:
manageElementData('myButton', 'set', 'status', 'inactive');
manageElementData('myButton', 'set', 'last-clicked', Date.now()); // Access as 'lastClicked' in JS

// Get all data attributes:
const allData = manageElementData('myButton', 'getAll');

// Remove a data attribute:
manageElementData('myButton', 'remove', 'userId');
How it works: The `dataset` property in JavaScript provides an easy way to access and manipulate custom data attributes (attributes prefixed with `data-`) on HTML elements. It returns a `DOMStringMap` object where each `data-name-attribute` becomes `element.dataset.nameAttribute` (camelCased). This snippet demonstrates how to set, get, remove, and retrieve all such attributes, offering a clean way to store small pieces of data directly on elements without polluting the global scope.

Need help integrating this into your project?

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

Hire DigitalCodeLabs