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
- Add data attributes in HTML:
html <button data-user-id="42" data-role="admin">Edit</button> - Read them in JavaScript:
javascript const btn = document.querySelector("button"); console.log(btn.dataset.userId); // "42" console.log(btn.dataset.role); // "admin" - Write or update values:
javascript btn.dataset.status = "active"; // HTML becomes data-status="active" - 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.stringifyandJSON.parse. - Data attributes are visible in the DOM; do not store sensitive information there.