Skip to content

HTML Tutorial Advanced and Practical HTML

HTML data Attributes: Storing Custom Data on Elements

Lesson 72 of 81 2 min read By Deepak Paswan Updated Oct 4, 2026

Sometimes you need to attach extra information to an element that HTML has no attribute for: a product id, a price, a state. That is what data-* attributes are for. You choose the name after data-.

index.html
HTML
<button data-book-id="42" data-price="14">Add The Slow Garden</button>

<script>
  document.querySelector("button").addEventListener("click", function () {
    this.textContent = "Added book " + this.dataset.bookId + " for $" + this.dataset.price;
  });
</script>

Reading them in JavaScript

JavaScript exposes them through dataset. The name data-book-id becomes dataset.bookId: hyphens turn into camelCase.

Using them in CSS

style.css
PHP
[data-status="sold-out"] { opacity: .5; }

Rules

  • Names are lowercase and use hyphens: data-user-id.
  • Values are always text. Convert to numbers in JavaScript when needed.
  • Do not store secrets. Anyone can read them with View source.
  • Do not use them for content visitors need to read. Put that in real elements.
lightbulb
Prefer them to made-up attributes
Writing <div price="14"> is invalid HTML. data-price is valid and future proof.