Categories
interview

HTML element as a datastore

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.

HTMLElement.dataset

<div id="demo" data-user="john"></div>
<script>
const element = document.getElementById('demo');

// Set a data attribute.
element.dataset.dateOfBirth = '2000-10-10';
// HTML: <div id="demo" data-user="john" data-date-of-birth="2000-10-10"></div>

delete element.dataset.dateOfBirth;
// HTML: <div id="demo" data-user="john"></div>
</script>

Demo