5 Matching Annotations
  1. Mar 2023
  2. Jun 2022
    1. The dataset read-only property of the HTMLElement interface provides read/write access to custom data attributes (data-*) on elements. It exposes a map of strings (DOMStringMap) with an entry for each data-* attribute.

      ```html

      <div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>

      ```

      ```js const el = document.querySelector('#user');

      // el.id === 'user' // el.dataset.id === '1234567890' // el.dataset.user === 'johndoe' // 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="johndoe" data-date-of-birth="1960-10-03">John Doe</div>

      delete el.dataset.dateOfBirth; // Result on JS: el.dataset.dateOfBirth === undefined // Result on HTML: <div id="user" data-id="1234567890" data-user="johndoe">John Doe</div>

      if ('someDataAttr' in el.dataset === false) { el.dataset.someDataAttr = 'mydata'; // Result on JS: 'someDataAttr' in el.dataset === true // Result on HTML: <div id="user" data-id="1234567890" data-user="johndoe" data-some-data-attr="mydata">John Doe</div> } ```