The dataset read-only property of the HTMLElement

Description

The dataset read-only property of the HTMLElement interface provides read/write access to custom data attributes ( https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-* ) (data-*) on elements.

It exposes a map of strings ( DOMStringMap ( https://developer.mozilla.org/en-US/docs/Web/API/DOMStringMap )) with an entry for each data-* attribute.

Note

The dataset property itself can be read, but not directly written. Instead, all writes must be to the individual properties within the dataset, which in turn represent the data attributes.

An HTML data-* attribute and its corresponding DOM dataset.property modify their shared name according to where they are read or written:

In HTML

The attribute name begins with data-. It can contain only letters, numbers, dashes (-), periods (.), colons (:), and underscores (_). Any ASCII capital letters (A to Z) are converted to lowercase.

In JavaScript

The property name of a custom data attribute is the same as the HTML attribute without the data- prefix, and removes single dashes (-) for when to capitalize the property’s “camelCased” name.

In addition to the information below, you’ll find a how-to guide for using HTML data attributes in our article ( https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes )

Examples

<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>
 1 const el = document.querySelector('#user');
 2
 3 // el.id === 'user'
 4 // el.dataset.id === '1234567890'
 5 // el.dataset.user === 'johndoe'
 6 // el.dataset.dateOfBirth === ''
 7
 8 // set a data attribute
 9 el.dataset.dateOfBirth = '1960-10-03';
10 // Result: el.dataset.dateOfBirth === '1960-10-03'
11
12 delete el.dataset.dateOfBirth;
13 // Result: el.dataset.dateOfBirth === undefined
14
15 if ('someDataAttr' in el.dataset === false) {
16   el.dataset.someDataAttr = 'mydata';
17   // Result: 'someDataAttr' in el.dataset === true
18 }

Other tutorials