Data Attributes
What Is It?
A data attribute stores a small piece of extra information on an element for your JavaScript to read.
What the Tags Mean
data-*: a custom data attribute.dataset: the JavaScript way to read it.data-price: becomes dataset.price.
Example 1
Save each example as index.html and open it in your browser. Each code block is a complete page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Attributes</title>
</head>
<body>
<p id="item" data-price="50">Notebook</p>
<script>
const item = document.getElementById("item");
item.textContent = "Notebook costs ₹" + item.dataset.price;
</script>
</body>
</html>Browser preview
What you see: The paragraph changes to Notebook costs ₹50.
Example 2: Another Use
Use another data attribute for an item category.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Attributes</title>
</head>
<body>
<article data-category="books">
<h2>My notebook</h2>
</article>
</body>
</html>Browser preview
Simple Tip
Data attributes are visible in page source. Do not store secrets in them.
Try It Yourself
Change the price and refresh the page.