Setting Data Attributes
You'll learn how to store and manipulate custom data on HTML elements using the dataset API.
What Are Data Attributes?
Data attributes are custom attributes you can add to HTML elements to store extra information. They always start with data- followed by your custom name. Think of them like sticky notes you attach to elements—they hold information without affecting how the element looks or behaves, but your JavaScript can read and modify them.
Using the dataset API
When you access an element's dataset property, you get an object containing all its data attributes. The naming convention automatically converts between HTML and JavaScript:
// HTML: <div id="user" data-user-id="123" data-role="admin"></div>
const userDiv = document.getElementById('user');
// Reading data attributes
console.log(userDiv.dataset.userId); // "123"
console.log(userDiv.dataset.role); // "admin"
// Setting data attributes
userDiv.dataset.lastLogin = "2024-01-15";
// Creates: data-last-login="2024-01-15" in HTML
userDiv.dataset.isActive = "true";
// Creates: data-is-active="true"
Naming Convention Rules
- HTML: Use lowercase with hyphens (
data-user-name) - JavaScript: Converts to camelCase (
dataset.userName) - Multi-word attributes automatically convert both ways
Understanding Value Types
All data attribute values are stored as strings, even if they look like numbers or booleans:
const box = document.getElementById('box');
box.dataset.count = 42;
console.log(typeof box.dataset.count); // "string", not "number"!
// Convert when needed
const actualCount = Number(box.dataset.count); // Now it's 42 as a number
Key Takeaway: Data attributes let you store custom information on elements using dataset, which automatically converts between kebab-case HTML attributes and camelCase JavaScript properties—but remember all values are strings.