How to use HTML data attributes to store extra information
· Category: HTML & CSS
Short answer
HTML5 data attributes allow you to store custom, private data on any element using attributes prefixed with data-. They are accessible via CSS and JavaScript without affecting validation or semantics.
Steps
- Add a
data-*attribute to any HTML element. - Read the value in JavaScript using
element.dataset.*(camelCase). - Style elements conditionally using attribute selectors like
[data-state="active"]. - Keep data small and serializable; avoid storing complex objects directly.
Example
<button data-user-id="42" data-role="admin">Edit User</button>
const btn = document.querySelector('button');
console.log(btn.dataset.userId); // "42"
console.log(btn.dataset.role); // "admin"
button[data-role="admin"] {
background: crimson;
color: white;
}
Tips
- Data attributes are string-only; cast numbers or booleans when reading.
- They are ideal for configuration and state flags, but avoid using them for data that should live in a database or API layer.
- They will not appear in search engine indexes, so do not rely on them for SEO-critical content.