JAVASCRIPT

Read and Write Custom Data Attributes on DOM Elements

Understand how to store and retrieve custom data directly within HTML elements using data attributes (`data-*`), providing a clean, standard way to associate metadata with your DOM nodes.

function manageDataAttributes(elementId, dataKey, newValue = null) {
    const element = document.getElementById(elementId);
    if (!element) {
        console.error(`Element with ID '${elementId}' not found.`);
        return null;
    }

    if (newValue !== null) {
        // Set/Update a data attribute
        element.dataset[dataKey] = newValue;
        console.log(`Set data-${dataKey} to: ${newValue}`);
    } else {
        // Read a data attribute
        const value = element.dataset[dataKey];
        console.log(`Read data-${dataKey}: ${value}`);
        return value;
    }
    return element.dataset[dataKey]; // Return the current value after setting/reading
}

// Example Usage:
// HTML: <div id="product-card" data-product-id="123" data-category="electronics">Product Info</div>

document.addEventListener('DOMContentLoaded', () => {
    const productId = manageDataAttributes('product-card', 'productId');
    console.log(`Initial Product ID: ${productId}`); // Output: Initial Product ID: 123

    const category = manageDataAttributes('product-card', 'category');
    console.log(`Product Category: ${category}`); // Output: Product Category: electronics

    // Update a data attribute
    manageDataAttributes('product-card', 'status', 'in-stock');
    console.log(`Updated Status: ${document.getElementById('product-card')?.dataset.status}`); // Output: Updated Status: in-stock

    // Add a new data attribute
    manageDataAttributes('product-card', 'price', '99.99');
    console.log(`New Price: ${document.getElementById('product-card')?.dataset.price}`); // Output: New Price: 99.99
});
How it works: This snippet demonstrates the use of the `dataset` property to interact with custom data attributes (`data-*`) on HTML elements. `element.dataset.keyName` provides a convenient way to read and write these attributes. The `dataKey` parameter corresponds to the part after `data-` (e.g., for `data-product-id`, `dataKey` would be `productId`). This method is invaluable for embedding small pieces of metadata directly into the DOM, which can then be easily accessed and manipulated by JavaScript without relying on element IDs or classes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs