Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to store custom data private to the page or application in HTML?
HTML data-* attributes allow you to store custom data directly within HTML elements. These attributes provide a standardized way to embed application-specific information that can be accessed via JavaScript and CSS without interfering with HTML semantics.
The data-* attributes are part of the HTML5 specification and offer a clean alternative to using non-standard attributes or hidden form fields for storing custom data. Any attribute name beginning with data- followed by at least one character is considered a valid data attribute.
Syntax
Following is the syntax for data-* attributes in HTML −
<element data-attribute-name="value">Content</element>
The attribute name after data- should be lowercase and can contain letters, numbers, hyphens, and underscores. Here are some valid examples −
<div data-user-id="123">User Profile</div> <button data-action="save" data-confirm="true">Save</button> <img data-original-width="800" data-original-height="600">
Accessing Data Attributes with JavaScript
JavaScript provides two ways to access data-* attributes: using getAttribute() method or the dataset property.
Using getAttribute() Method
const element = document.getElementById('myElement');
const value = element.getAttribute('data-user-id');
Using dataset Property
The dataset property provides a more convenient way to access data attributes. Note that hyphens in attribute names are converted to camelCase −
const element = document.getElementById('myElement');
const userId = element.dataset.userId; // data-user-id
const isConfirm = element.dataset.confirm; // data-confirm
Example − Reading Data Attributes
Following example demonstrates how to read custom data attributes using JavaScript −
<!DOCTYPE html>
<html>
<head>
<title>Reading Data Attributes</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Competition Results</h2>
<ul>
<li onclick="showPosition(this)"
id="Siddarth" data-position="winner" data-score="95">
Siddarth
</li>
<li onclick="showPosition(this)"
id="Arjun" data-position="runner-up" data-score="87">
Arjun
</li>
<li onclick="showPosition(this)"
id="Badri" data-position="third" data-score="82">
Badri
</li>
<li onclick="showPosition(this)"
id="Nanda" data-position="fourth" data-score="78">
Nanda
</li>
</ul>
<script>
function showPosition(runner) {
const position = runner.getAttribute("data-position");
const score = runner.dataset.score;
const name = runner.innerHTML.trim();
alert(name + " finished " + position + " with a score of " + score);
}
</script>
</body>
</html>
Clicking on any name displays an alert showing both the position and score data −
Competition Results ? Siddarth ? Arjun ? Badri ? Nanda (Clicking "Siddarth" shows: "Siddarth finished winner with a score of 95")
Setting Data Attributes with JavaScript
You can also modify or add data attributes dynamically using JavaScript −
Example − Setting Data Attributes
<!DOCTYPE html>
<html>
<head>
<title>Setting Data Attributes</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<div id="product" data-price="100">Laptop</div>
<button onclick="applyDiscount()">Apply 20% Discount</button>
<button onclick="showPrice()">Show Current Price</button>
<p id="result"></p>
<script>
function applyDiscount() {
const product = document.getElementById('product');
const originalPrice = parseInt(product.dataset.price);
const discountedPrice = originalPrice * 0.8;
// Set new data attributes
product.dataset.originalPrice = originalPrice;
product.dataset.price = discountedPrice;
product.dataset.discount = "20%";
document.getElementById('result').textContent =
'Discount applied! New price: $' + discountedPrice;
}
function showPrice() {
const product = document.getElementById('product');
const price = product.dataset.price;
const discount = product.dataset.discount || 'None';
document.getElementById('result').textContent =
'Current price: $' + price + ', Discount: ' + discount;
}
</script>
</body>
</html>
This example shows how to dynamically update data attributes and retrieve the updated values −
Laptop [Apply 20% Discount] [Show Current Price] (After clicking "Apply 20% Discount": "Discount applied! New price: $80") (Clicking "Show Current Price" then shows: "Current price: $80, Discount: 20%")
Accessing Data Attributes with CSS
CSS can access data attributes using the attr() function, which is commonly used with pseudo-elements like ::before and ::after −
element::before {
content: attr(data-attribute-name);
}
Example − Using Data Attributes in CSS
<!DOCTYPE html>
<html>
<head>
<title>CSS Data Attributes</title>
<style>
.tooltip {
position: relative;
display: inline-block;
padding: 10px 15px;
background-color: #007bff;
color: white;
cursor: pointer;
border-radius: 4px;
margin: 10px;
}
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
bottom: 125%;
left: 50%;
transform: translateX(-50%);
background-color: #333;
color: white;
padding: 5px 10px;
border-radius: 4px;
white-space: nowrap;
opacity: 0;
visibility: hidden;
transition: opacity 0.3s;
font-size: 12px;
}
.tooltip:hover::after {
opacity: 1;
visibility: visible;
}
.status::before {
content: "Status: " attr(data-status);
display: block;
font-size: 14px;
color: #666;
margin-bottom: 5px;
}
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>CSS Data Attributes Demo</h2>
<div class="tooltip" data-tooltip="This is a save button">Save</div>
<div class="tooltip" data-tooltip="Click to cancel the operation">Cancel</div>
<div class="status" data-status="Active">User Account</div>
<div class="status" data-status="Pending">Order #1234</div>
</body>
</html>
The CSS uses data attributes to display tooltips on hover and status labels −
CSS Data Attributes Demo [Save] [Cancel] (Blue buttons, show tooltips on hover) Status: Active User Account Status: Pending Order #1234
Best Practices
When using data attributes, follow these best practices −
Use lowercase with hyphens − Keep attribute names lowercase and use hyphens to separate words:
data-user-nameinstead ofdata-userName.Keep values as strings − Data attributes store string values. Use
parseInt()orparseFloat()when you need numeric values in JavaScript.Avoid sensitive data − Data attributes are visible in the HTML source, so never store passwords or sensitive information.
Use meaningful names − Choose descriptive attribute names that clearly indicate their purpose:
data-product-id,data-sort-order.Consider performance − For large datasets, consider using JavaScript objects instead of many data attributes.
Common Use Cases
Data attributes are commonly used for −
Configuration data − Storing widget settings, API endpoints, or feature flags.
State management − Tracking UI states like active tabs, expanded sections, or loading states.
Metadata − Additional information about elements like creation dates, authors,
