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>
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);
The output:
DOMStringMap {region: "San Francisco"}
San Francisco
1.23
2.46
one item
another item
- It is to attach additional data to HTML elements.
- Will not affect how the element is displayed.
- This is a standard way to attach additional information to the DOM element.
- It begins with
data-
in the HTML - In JavaScript, when we have the DOM element, we can use the
dataset
property to get to the data - if it is
data-a
in the HTML, then it isel.dataset.a
in JavaScript, whereel
is the element - Hyphenated case (kebab case) becomes camel case. For example,
data-hello-world
becomesdataset.helloWorld
- It is supported in all modern browsers
- Some docs on MDN and JavaScript: The Definitive Guide, 7th Ed.
Top comments (0)