DEV Community

Kenneth Lum
Kenneth Lum

Posted on • Edited on

1

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.

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay