Data Attributes
A script on a recipe page needs to know each recipe's cooking time so it can filter quick meals. The number is not something you want printed on every card, and there is no standard attribute called cooking-time. Inventing one would be invalid HTML. Data attributes are the official way to attach your own information to an element.
The rule
Your own attribute must start with data-.
Any attribute whose name begins with data- is valid on any element, and its meaning is up to you:
<article class="recipe" data-minutes="15" data-diet="vegan">
<h3>Lemon Rice</h3>
<p>Leftover rice, curry leaves, peanuts and lemon.</p>
</article>The rules:
- The name is
data-followed by at least one character, in lowercase. Hyphens are fine:data-release-year. - The value is always text.
data-minutes="15"holds the string"15", which a script must convert if it wants a number. - Browsers do nothing with them by themselves. They are storage for your code.
JavaScript can read them through the element's dataset, where hyphenated names turn into camelCase:
const card = document.querySelector(".recipe");
card.dataset.minutes; // "15"
card.dataset.diet; // "vegan"
// data-release-year would be card.dataset.releaseYearCSS can select by them too, for example [data-diet="vegan"].
What data attributes are not for: content people need to read (put that in visible text), or anything secret. Everything in your HTML can be read by anyone through "View source".
The shortcut
When you want to attach a fact to an element, ask: "Is there already a standard attribute for this?" If yes, use it (href, alt, lang, datetime...). If no, and it is for your code only, prefix data-.
The fact: which city each event is in
Readers want to see the city, so it goes in the visible text of each event.
The trap is inventing unprefixed attributes such as minutes="15" or price="99". Browsers ignore them, validators flag them, and a future HTML version could give that name a real meaning.
Drills
Answer fast — trust the rule.
Which is a valid custom attribute?
A script reads el.dataset.quantity from data-quantity="3". What type of value does it get?
How is data-publish-date accessed through dataset?
A developer stores a user's discount code in data-coupon so only the script sees it. What is the problem?
Remember
- Custom attributes must start with
data-, use lowercase names, and always hold strings. - Shortcut: use a standard attribute if one exists; otherwise, for your code only, prefix
data-. - Trap: invented unprefixed attributes, and storing secrets or needed content in them.
