HTML Custom Data Attributes and Dataset
Attach application metadata
Use a data-* attribute for application-specific information with no predefined HTML meaning. The attribute name begins with data- followed by a custom name. Use native attributes for built-in meaning and visible content for user-facing information.
<article id="course" data-course-id="html-101"> <h2>HTML basics</h2></article>The identifier is stored on the article, while the visible heading describes the course.
Read a camel-case key
The dataset property is a mapping of data attributes to strings. A hyphen followed by a lowercase ASCII letter becomes the corresponding uppercase letter: data-course-id becomes dataset.courseId. A dot accesses a named property. Use Number when a numeric calculation is required.
<p id="item" data-unit-price="5">Notebook</p><output id="total"></output><script> const item = document.getElementById("item"); document.getElementById("total").textContent = Number(item.dataset.unitPrice) * 3;</script>The displayed total is 15, not a concatenated string.
Write and remove data
Assigning a dataset property updates the corresponding attribute and converts values to strings. The delete operator removes a property and its attribute. CSS may also select elements using attribute selectors such as [data-state="done"].
<p id="task" data-state="new" data-temp="yes">Review</p><script> const task = document.getElementById("task"); task.dataset.state = "done"; delete task.dataset.temp;</script>The state becomes done and data-temp is removed.
Common mistakes and practice
Data attributes are visible and editable in developer tools. Never use them as proof of authorization or a place for secrets. They do not provide accessible names or roles and do not automatically participate in form submission. The string "false" is not a Boolean false in JavaScript.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Custom Data Attributes and Dataset — Knowledge Check
Apply the integration concepts taught in this lesson.
Which attribute name follows the custom data convention?
How is data-course-id read through dataset?
What type is a dataset value when present?
What does delete element.dataset.state do?
Can data attributes protect secrets from the user?