HTML - data-* attributes

What it actually means

data-* attributes let you attach custom, non-visual data to HTML elements without breaking standards. This data can be read safely by JavaScript or CSS.


How to use it correctly

Syntax:

<div data-user-id="42" data-status="active"></div>

Access in JavaScript:

element.dataset.userId
element.dataset.status

Rules:

  • Use lowercase and hyphen-separated names

  • Store only small, relevant values

  • Do not store sensitive data


Why this matters

  • Keeps HTML and JavaScript loosely coupled

  • Avoids hardcoding logic in JS files

  • Makes dynamic behavior easier to manage

  • Used heavily in frameworks and UI libraries

Cleaner than abusing classes or hidden inputs.


Common misuse

Bad:

<div class="user-42-active"></div>

Correct:

<div data-user-id="42" data-active="true"></div>

Practical rule

If data is needed by JavaScript but not visible to users, use data-*, not classes or inline scripts.