HTML5
What are Custom Attributes in HTML5?
HTML5 introduced custom data attributes, written as data-*, that let you attach arbitrary private data to any HTML element without breaking validation. You choose the name after data-, store a value, and read it back easily in JavaScript through the element's dataset property.
What Are data-* Attributes?
A custom attribute is any attribute whose name starts with data- followed by at least one lowercase character, for example data-user-id or data-price. They are valid HTML5, do not affect rendering, and are meant to hold custom data for scripts to use.
The Naming Rule and dataset Mapping
| HTML attribute | JavaScript dataset property |
|---|---|
| data-id | element.dataset.id |
| data-user-name | element.dataset.userName |
| data-max-count | element.dataset.maxCount |
Hyphenated names become camelCase in dataset: data-user-name is read as dataset.userName. Values are always strings, so convert with Number() or JSON.parse() when needed.
Runnable Interactive Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Data Attributes</title>
</head>
<body>
<h2>Product List</h2>
<button data-id="101" data-price="499" onclick="show(this)">Pen Drive</button>
<button data-id="102" data-price="1299" onclick="show(this)">Keyboard</button>
<p id="out">Click a product to see its data.</p>
<script>
function show(btn) {
var id = btn.dataset.id;
var price = Number(btn.dataset.price);
document.getElementById("out").textContent =
"Product ID " + id + " costs Rs. " + price;
}
</script>
</body>
</html>Common Uses
- Storing an item id or price for JavaScript event handlers.
- Passing configuration to a widget without extra markup.
- Filtering or sorting lists based on data-category values.
- Holding state for CSS attribute selectors like [data-active].
data-* attributes are for private data used by YOUR scripts. Do not store sensitive information in them — they are visible in page source.
Key Takeaways
- Custom attributes use the data-* prefix and are valid HTML5.
- Read them in JavaScript via element.dataset (camelCased).
- Values are always strings — convert types as needed.
- Great for attaching per-element data to scripts and CSS.
