JavaScriptDOM and events

HTMLElement.dataset

An object with an element’s data-* attribute values, for reading and storing your own data.

Returns
A DOMStringMap object with the data-* attribute values stored as strings.
On this page

Example

#
JavaScript
const course = document.querySelector('#course')

console.log(course.dataset.courseId)
console.log(Number(course.dataset.price) * 2)
console.log(course.dataset.premium === 'true')
console.log(course.dataset)
Console
42
98
true
DOMStringMap { courseId: '42', price: '49', premium: 'true' }

Definition and usage

#

Attributes starting with data- let you store your own information in HTML, such as a course id or a product price. The dataset property exposes them as an object: the data-course-id attribute is available as dataset.courseId. The part of the name after each hyphen starts with a capital letter (camelCase).

Every value in dataset is a string. You need to convert a number with Number(), and compare a boolean value against a string, e.g. dataset.premium === "true". Assigning a new value creates or changes the attribute in the HTML, and delete element.dataset.name removes it.

data-* attributes work great for event delegation: one function handles many buttons, and each button carries information about what it refers to. You can also style elements in CSS with an attribute selector, e.g. [data-status="done"].

Syntax

#
Syntax
element.dataset.name
element.dataset.name = value
delete element.dataset.name

More examples

#
Writing and removing data
JavaScript
const task = document.querySelector('#task')

task.dataset.status = 'done'
task.dataset.completedAt = '2026-09-28'

console.log(task.getAttribute('data-status'))
console.log(task.getAttribute('data-completed-at'))

delete task.dataset.completedAt
console.log(task.hasAttribute('data-completed-at'))
Console
done
2026-09-28
false
Event delegation with data-*
JavaScript
const shop = document.querySelector('#shop')

shop.addEventListener('click', (event) => {
  const { item, cost } = event.target.dataset
  if (!item) return
  console.log(`Buying: ${item} for ${cost} coins`)
})

shop.querySelector('[data-item="theme"]').click()
Console
Buying: theme for 250 coins

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Remember that dataset returns strings. dataset.price + 1 gives "491", not 50. Convert the value with Number().
  • In HTML, write names in lowercase with hyphens (data-course-id), and in JavaScript read them in camelCase (dataset.courseId).
  • Don’t store sensitive data in data-*. Anyone can see it in the page’s code.

Related entries

#

Spotted a mistake or missing an example? Write to us.