How do data attributes work in JavaScript?
A data attribute is a custom attribute on an HTML element whose name starts with data-. It lets you attach your own information to an element without inventing a new attribute or using a non-standard one. The dataset object gives you typed access to those attributes.
// The DOM only exists in a browser, so check before using it.
if (typeof document !== "undefined") {
const button = document.createElement("button");
button.dataset.userId = "42";
button.dataset.role = "admin";
console.log(button.dataset.userId); // "42"
console.log(button.getAttribute("data-user-id")); // "42"
console.log(button.dataset.role); // "admin"
console.log(Object.keys(button.dataset)); // ["userId", "role"]
} else {
console.log("No DOM in this runtime - open a browser console to try it.");
}The naming rule is the detail that trips people up. In the attribute itself you write a hyphenated name such as data-user-id, and in the dataset object the same attribute appears as the camelCase key userId. Setting dataset.userId writes the attribute data-user-id, and reading it back gives you the same string. Values are always strings, because that is what attributes hold.
Data attributes are a good fit for values that describe an element for your own code to read later, such as an id, a role or a state. They are a poor fit for values that drive styling, because you cannot select on an attribute value and keep the styling in one place the way you can with classes. And they are not a place to put application state, because they are visible in the markup and in the inspector, and they survive page loads in ways that surprise people.