How to work with dataset and custom data attributes

· Category: JavaScript

Short answer

The dataset API provides camelCase access to HTML data-* attributes, letting you store arbitrary strings on elements without invalidating your markup.

Steps

  1. Add data attributes in HTML: html <button data-user-id="42" data-role="admin">Edit</button>
  2. Read them in JavaScript: javascript const btn = document.querySelector("button"); console.log(btn.dataset.userId); // "42" console.log(btn.dataset.role); // "admin"
  3. Write or update values: javascript btn.dataset.status = "active"; // HTML becomes data-status="active"
  4. Remove an attribute: javascript delete btn.dataset.role;

Tips

  • All values are strings; cast to numbers or booleans explicitly when needed.
  • Keep attribute names lowercase with hyphens in HTML; access them in camelCase in JavaScript.

Common issues

  • Storing complex objects as JSON strings requires manual JSON.stringify and JSON.parse.
  • Data attributes are visible in the DOM; do not store sensitive information there.