HTMLElement. dataset
An object with an element’s data-* attribute values, for reading and storing your own data.
- Returns
- A
DOMStringMapobject with thedata-*attribute values stored as strings.
Example
#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)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
#element.dataset.name
element.dataset.name = value
delete element.dataset.nameMore examples
#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'))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()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
datasetreturns strings.dataset.price + 1gives"491", not50. Convert the value withNumber(). - 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
#- Element.setAttribute()Sets the value of an element’s HTML attribute, or adds a new attribute.
- Event.targetThe element on which an event actually occurred, for example the clicked button inside a list.
- Element.classListAn object for adding, removing, toggling, and checking an element’s CSS classes.
- document.querySelector()Returns the first element that matches a CSS selector, or null when nothing matches.
- Number.parseInt()Converts the start of a string into an integer in a given numeral system.
Spotted a mistake or missing an example? Write to us.