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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more