DEV Community

Kenneth Lum
Kenneth Lum

Posted on • Edited on

We can use the dataset property with the `data-` attribute

An example first, and then we can go into some details. Example:

https://jsfiddle.net/KennethKinLum/o70ayk19/

<div id="foo" data-region="San Francisco">Hello</div>

<ul id="my-list">
  <li data-crypto-value="1.23">$51234</li>
  <li data-crypto-value="2.46">$102468</li>
</ul>

<div id="bar" data-a="one item" data-b="another item">Hello</div>
Enter fullscreen mode Exit fullscreen mode
console.log(document.querySelector("#foo").dataset);

console.log(document.querySelector("#foo").dataset.region);

document.querySelectorAll("#my-list li")
  .forEach(e => console.log(e.dataset.cryptoValue));

console.log(document.querySelector("#bar").dataset.a);
console.log(document.querySelector("#bar").dataset.b);

Enter fullscreen mode Exit fullscreen mode

The output:

DOMStringMap {region: "San Francisco"}
San Francisco
1.23
2.46
one item
another item
Enter fullscreen mode Exit fullscreen mode
  1. It is to attach additional data to HTML elements.
  2. Will not affect how the element is displayed.
  3. This is a standard way to attach additional information to the DOM element.
  4. It begins with data- in the HTML
  5. In JavaScript, when we have the DOM element, we can use the dataset property to get to the data
  6. if it is data-a in the HTML, then it is el.dataset.a in JavaScript, where el is the element
  7. Hyphenated case (kebab case) becomes camel case. For example, data-hello-world becomes dataset.helloWorld
  8. It is supported in all modern browsers
  9. Some docs on MDN and JavaScript: The Definitive Guide, 7th Ed.

Top comments (0)