HTML data-* attributes are used to store custom data directly in HTML element.
Definition and Usage
➔ This custom data stored by the data-* attributes is private to the page or application.
Syntax
//In HTML
<div id="sample" data-item-id="52245" data-category="fruits" data-stock="25">
Apple
</div>
//In Javascript
<script>
// This anonymous function runs as soon as it's encountered.
(() => {
let element = document.getElementById("sample");
let oldstock = element.dataset.stock;
//element.dataset.stock = "50";
//let itemId = element.dataset.itemId;
//using setAttribute
element.setAttribute('data-stock', '50');
let newstock = element.getAttribute("data-stock");
alert("New Stock is: " + newstock + "\nOld Stock is: " + oldstock);
})();
</script>
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| data-* | Global Attributes |
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML data-* attribute example</title>
<meta charset="utf-8" />
</head>
<body>
<h3>HTML data-* attribute example</h3>
<p>data-* attributes are used to store custom data directly in HTML element.</p>
<div id="sample" data-item-id="52245" data-category="fruits" data-stock="25">
Apple
</div>
<script>
// This anonymous function runs as soon as it's encountered.
(() => {
let element = document.getElementById("sample");
let oldstock = element.dataset.stock;
//element.dataset.stock = "50";
//let itemId = element.dataset.itemId;
//using setAttribute
element.setAttribute('data-stock', '50');
let newstock = element.getAttribute("data-stock");
alert("New Stock is: " + newstock + "\nOld Stock is: " + oldstock);
})();
</script>
</body>
</html
Click on the "Try it Now" button to see how it works.