190 of 264 menu

dataset property

In HTML, it is allowed to add custom attributes to tags, and they must begin with data-, and then any attribute name must follow. To access such attributes through JavaScript, use the special dataset property.

Syntax

element.dataset.name;

Example

Let's read the attribute value:

<div data-cost="1000"></div> let elem = document.querySelector('div'); let res = elem.dataset.cost; console.log(res);

The code execution result:

'1000'

Example

Let's change the attribute value:

<div data-cost="1000"></div> let elem = document.querySelector('div'); elem.dataset.cost = '2000';

As a result, the code will look like this:

<div data-cost="2000"></div>

See also

byenru