Kodokon kodokon.com

Global attributes and data-*

Leverage the attributes that work everywhere and store your own data in the HTML.

7 min · 3 questions

Open this lesson in Kodokon

Some attributes work on any element: these are the global attributes. You already use id and class; add to your toolbox hidden (hides the element), lang (indicates the language of a passage), title (tooltip on hover) and tabindex (keyboard focus order).

HTML
<p lang="en" title="Original quote">
  Stay hungry, stay foolish.
</p>

<div hidden id="cookie-banner" class="banner">
  We use cookies.
</div>
lang, title and hidden in a real situation.

Need to attach your own data to an element? Never invent a made-up attribute: HTML reserves the data-* attributes for exactly that. You choose the name after the dash, in lowercase kebab-case. Typical use cases: a product identifier, a UI state, a component configuration.

HTML
<article
  class="product-card"
  data-product-id="42"
  data-category="books"
  data-in-stock="true"
>
  <h2>HTML for pros</h2>
</article>
Business data attached to a product card.

On the JavaScript side, these attributes are read through the dataset property. Watch out for the automatic conversion: the HTML kebab-case becomes camelCase in JavaScript. So data-product-id is read with dataset.productId. The values are always strings, even "true" or "42".

JAVASCRIPT
const card = document.querySelector(".product-card");

console.log(card.dataset.productId); // "42"
console.log(card.dataset.inStock);   // "true"

card.dataset.state = "selected";
Reading and writing data-* through dataset.

Knowledge check

Make sure you remember the key points of this lesson.

  1. How do you read the data-user-id attribute in JavaScript?
    • element.dataset.userId
    • element.dataset.user-id
    • element.data.userId
    • element.getData("user-id")
  2. What are data-* attributes for?
    • Storing custom data your JavaScript can read
    • Speeding up the loading of the page's data
    • Sending data to the server when a form is submitted
  3. Which global attribute hides an element semantically?
    • hidden
    • invisible
    • display