docs.rodeo

MDN Web Docs mirror

HTMLElement: dataset property

{{APIRef("HTML DOM")}} 

The dataset read-only property of the {{DOMxRef("HTMLElement")}}  interface provides read/write access to custom data attributes (data-*) on elements. It exposes a map of strings ({{domxref("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:

Details and examples of converting between the HTML and JavaScript forms is described in more detail in the next section.

In addition to the information below, you’ll find a how-to guide for using HTML data attributes in our article Using data attributes.

Name conversion

For example, a data-abc-def attribute corresponds to dataset.abcDef.

Accessing values

Setting values

Value

A {{domxref("DOMStringMap")}} .

Examples

<div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth>
  Carina Anand
</div>
const el = document.querySelector("#user");

// el.id === 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'carinaanand'
// el.dataset.dateOfBirth === ''

// set a data attribute
el.dataset.dateOfBirth = "1960-10-03";
// Result on JS: el.dataset.dateOfBirth === '1960-10-03'
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth="1960-10-03">Carina Anand</div>

delete el.dataset.dateOfBirth;
// Result on JS: el.dataset.dateOfBirth === undefined
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand">Carina Anand</div>

if (el.dataset.someDataAttr === undefined) {
  el.dataset.someDataAttr = "mydata";
  // Result on JS: 'someDataAttr' in el.dataset === true
  // Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand" data-some-data-attr="mydata">Carina Anand</div>
}

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN