How do data attributes work in JavaScript?
A data attribute is an extra attribute that you put on an HTML element, and its name always starts with data-. It lets you attach your own information to an element without inventing a new kind of attribute. The dataset object gives you a clean way to read and write those attributes from JavaScript.
// 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);
console.log(button.getAttribute('data-user-id'));
console.log(button.dataset.role);
console.log(Object.keys(button.dataset));
} 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 shows up as the camelCase key userId. Setting button.dataset.userId writes the attribute data-user-id into the markup, and reading it back gives you the same string. The values are always strings, because that is all an attribute can hold.
Data attributes are a good fit for values that describe an element so that your own code can read them later, such as an id, a role, or a state. They are a poor fit for values that control styling, because you cannot select on an attribute value and keep the styling in one place the way you can with classes. They are also not a good place for application state, because they are visible in the markup and in the inspector, and they survive page loads in ways that surprise people.