JAVASCRIPT

Manage Custom Data Attributes for Dynamic Content

Explore how to read and update `data-*` attributes on HTML elements using JavaScript, enabling flexible data storage and manipulation for interactive components.

/* Example HTML structure for context:
<button id="myButton" data-user-id="123" data-status="active">Click Me</button>
*/

const button = document.getElementById('myButton');

// Read a data attribute
const userId = button.dataset.userId; // '123' (note camelCase)
const status = button.dataset.status; // 'active'
console.log('User ID:', userId, 'Status:', status);

// Update a data attribute
button.dataset.status = 'inactive';
console.log('New Status:', button.dataset.status);

// Add a new data attribute
button.dataset.role = 'admin';
console.log('Role:', button.dataset.role);

// Data attributes are always strings, convert if needed:
// const numericId = parseInt(button.dataset.userId, 10);
How it works: HTML `data-*` attributes allow you to store custom data directly on standard HTML elements, making them accessible via JavaScript. The `dataset` property of an element provides a convenient way to access these attributes. Attribute names like `data-user-id` are camelCased to `dataset.userId` in JavaScript. This technique is invaluable for attaching state, IDs, or configuration data to elements without relying on global variables or complex data structures, simplifying component interaction.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs