Data Attributes for Custom Data
Uses data attributes to store custom data in HTML elements, accessed via JavaScript dataset API for configuration and state management.
Code
<div id="user-profile"
data-user-id="42"
data-user-name="Alice"
data-role="admin"
data-active="true"
data-last-login="2025-01-15">
<h2>User Profile</h2>
<p>Click to view details</p>
</div>
<button class="action-btn"
data-action="delete"
data-confirm="Are you sure?"
data-endpoint="/api/users/42"
data-method="DELETE">
Delete User
</button>
<ul class="todo-list">
<li data-todo-id="1" data-completed="false">Buy groceries</li>
<li data-todo-id="2" data-completed="true">Walk the dog</li>
<li data-todo-id="3" data-completed="false">Do laundry</li>
</ul>
<script>
const profile = document.getElementById('user-profile');
console.log(profile.dataset.userId);
console.log(profile.dataset.userName);
console.log(profile.dataset.role);
console.log(profile.dataset.active === 'true');
document.querySelectorAll('.action-btn').forEach(btn => {
btn.addEventListener('click', async () => {
const { action, confirm: msg, endpoint, method } = btn.dataset;
if (msg && !window.confirm(msg)) return;
const response = await fetch(endpoint, { method });
console.log(`${action} completed`);
});
});
document.querySelectorAll('.todo-list li').forEach(item => {
item.addEventListener('click', () => {
const id = item.dataset.todoId;
const completed = item.dataset.completed === 'true';
item.dataset.completed = !completed;
item.style.textDecoration = !completed ? 'line-through' : 'none';
});
});
</script>data-* attributes store custom data directly on HTML elements. JavaScript accesses them via element.dataset (camelCase conversion: data-user-id becomes dataset.userId). They’re useful for configuration, state, and passing data to event handlers. Avoid storing large data or sensitive information. Use JSON.parse() for complex values stored as JSON strings.
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
Report a problem with this exampleOpens a pre-filled issue on GitHub.