HTML Course 14.3 Data attributes (data-*) to connect HTML and JS

Course 14.3: Data attributes (data-*) to connect HTML and JavaScript

HTML5 introduced custom data attributes—attributes whose names start with data-. They allow embedding extra information in HTML elements that can be read and manipulated in JavaScript via the Element.dataset API.

1. Syntax and Naming Conventions

  • Any attribute name beginning with data- is valid.
  • After data-, use only lowercase letters, digits, hyphens.
  • In JavaScript, the attribute name maps to element.dataset properties in camelCase. Example: data-user-id → dataset.userId.
HTML attribute JavaScript property
data-product-name dataset.productName
data-id dataset.id
data-abc-def-ghi dataset.abcDefGhi

2. Accessing Data Attributes in JavaScript

Every element has a dataset property, an object reflecting its data attributes.

  • Get value: element.dataset.keyName
  • Set value: element.dataset.keyName = 'value' (updates the DOM attribute)
  • Enumerate all: Object.keys(element.dataset) or for (let key in element.dataset).

3. Common Use Cases

  1. Passing configuration to scripts (e.g. data-theme='dark').
  2. Storing identifiers for event handlers (e.g. data-user-id).
  3. Toggle states (e.g. data-expanded='true').
  4. Lazy loading (e.g. data-src for images).
  5. Analytics and tracking (e.g. data-tracking-id).

4. Example 1: Basic Reading and Writing





5. Example 2: Looping Through Data Attributes

User Card

6. Example 3: Event Handling with Data Attributes

  • Item A
  • Item B
  • Item C