Back to subject
HTML5/HTML Data Attributes

Store Small Pieces of Information

Practical lesson

Let's store a small piece of custom data directly on an HTML element.

- Start with a normal element such as a button or article. - Add an attribute such as data-user-id="42". - The data- prefix is important because it tells the browser that this is custom data intended for the page or its scripts. - You can create names such as data-category, data-product-id, or data-state. - Keep the value simple and meaningful so JavaScript can read it later. - data-* attributes are not a replacement for class or id. Use class for grouping and id for unique identification. - Do not use data-* when a standard HTML attribute already expresses the information you need. - In JavaScript, these values can be accessed through an element's dataset.

The main lesson is that data-* gives your HTML a standard place to store small custom values without inventing non-standard attributes.

Try it yourself
Code

Starter example

Code
<button data-product-id="42" data-category="books">Buy</button>
Live preview