JAVASCRIPT

Managing Element Data with Custom Data Attributes

Learn to store and retrieve small pieces of custom data directly on HTML elements using data attributes (`data-*`) for client-side JavaScript logic.

function handleProductSelection(productId, action) {
    const productElement = document.getElementById(`product-${productId}`);
    if (productElement) {
        if (action === 'select') {
            // Read data attribute
            const price = productElement.dataset.price;
            const category = productElement.dataset.category;
            productElement.classList.add('selected');
            console.log(`Selected product ID: ${productId}, Price: $${price}, Category: ${category}`);

            // Update a data attribute
            productElement.dataset.status = 'addedToCart';
            console.log(`Product status updated to: ${productElement.dataset.status}`);

        } else if (action === 'deselect') {
            productElement.classList.remove('selected');
            productElement.dataset.status = 'available';
            console.log(`Deselected product ID: ${productId}. Status: ${productElement.dataset.status}`);
        }
    } else {
        console.error(`Product element with ID "product-${productId}" not found.`);
    }
}

// Example Usage:
// Assuming HTML like this:
// <div id="product-101" class="product-card" data-price="29.99" data-category="Electronics">
//   <h3>Gadget X</h3>
//   <button onclick="handleProductSelection(101, 'select')">Add to Cart</button>
//   <button onclick="handleProductSelection(101, 'deselect')">Remove</button>
// </div>
// <div id="product-102" class="product-card" data-price="12.50" data-category="Books">
//   <h3>Book Y</h3>
//   <button onclick="handleProductSelection(102, 'select')">Add to Cart</button>
// </div>

// Initial call (e.g., from a button click)
// handleProductSelection(101, 'select');
How it works: HTML `data-*` attributes allow you to embed custom data directly into HTML elements. This snippet demonstrates how to access and modify these attributes using the `element.dataset` property in JavaScript. It's a clean way to store small, element-specific pieces of information (like IDs, prices, or statuses) that can be easily retrieved and updated by client-side scripts without relying on global variables or complex DOM traversal.

Need help integrating this into your project?

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

Hire DigitalCodeLabs