JAVASCRIPT

Read and Write Custom Data Attributes with `dataset`

Learn how to easily access and modify custom HTML5 `data-*` attributes on DOM elements using the convenient `dataset` property in JavaScript.

function manageDataAttribute(elementId) {
    const element = document.getElementById(elementId);
    if (!element) {
        console.error('Element not found:', elementId);
        return;
    }

    // --- Reading Data Attributes ---

    // HTML: <div id="my-element" data-user-id="123" data-status="active"></div>

    // Access via dataset property
    const userId = element.dataset.userId; // '123'
    const status = element.dataset.status; // 'active'

    console.log(`Initial User ID: ${userId}, Status: ${status}`);

    // --- Writing/Updating Data Attributes ---

    // Update an existing data attribute
    element.dataset.status = 'inactive';
    console.log('Updated Status:', element.dataset.status); // 'inactive'

    // Add a new data attribute
    element.dataset.lastUpdated = new Date().toISOString();
    console.log('New Data Attribute (lastUpdated):', element.dataset.lastUpdated);

    // --- Removing Data Attributes ---
    // delete element.dataset.status;
    // console.log('Status after removal:', element.dataset.status); // undefined
}

// Example Usage:
// Assuming this HTML:
// <div id="data-element" data-user-id="456" data-theme="dark">Content</div>
manageDataAttribute('data-element');
How it works: HTML5 `data-*` attributes provide a way to store custom data directly on DOM elements. This snippet demonstrates how to interact with these attributes using the `element.dataset` property. `dataset` provides a convenient object-like interface where `data-user-id` becomes `dataset.userId` (camelCased). It allows for easy reading, updating, and adding of these custom attributes, making it a valuable tool for dynamic UI logic without relying on global JavaScript variables.

Need help integrating this into your project?

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

Hire DigitalCodeLabs