JavaScript: dataset
The dataset property reads and changes custom data-* attributes on HTML elements.
What you will learn
- How to read and change
data-*values - How dashed attribute names become camelCase properties
- Why dataset values are always strings and how to use them for state
Minimal example
<button id="save" data-action="save" data-user-name="Aki">Save</button>
<script>
const button = document.querySelector("#save");
console.log(button.dataset.action); // "save"
console.log(button.dataset.userName); // "Aki"
button.dataset.state = "ready";
</script>The data- prefix is removed, and each following hyphen changes the next letter to uppercase: data-user-name becomes dataset.userName. Assigning a value updates the corresponding HTML attribute.
Important points
- Dataset values are strings, so compare
dataset.countwith"1"or convert it withNumber(). - Use
delete element.dataset.nameto remove an attribute; assigning an empty string leaves the attribute present. - Use
closest()when a click may land on a child element instead of the element carrying the data attribute. - Do not treat data attributes as a security boundary; validate important values before using them.