Render in cart items using JS

I am trying to display my objects in a shopping cart once the user clicks on the “Purchase” button but I can’t seem to get it right. I’ve managed to display a single item thus far when clicked but it does not loop to any of the others.

My idea was to target the data-id of each button, listen for the id and render the object based off of that, but I’m not pro enough just yet to know how to do that myself 😛

Any help would be greatly appreciated ^^

const cartBtn = document.querySelector(`.cart-btn`);//
const closeCartBtn = document.querySelector(`.close-cart`);//
const clearCartBtn = document.querySelector(`.clear-cart`);//
const cartDOM = document.querySelector(".cart");
const cartOverlay = document.querySelector(`.cart-overlay`);
const cartItems = document.querySelector(".cart-items");
const cartTotal = document.querySelector(".cart-total");
const cartContent = document.querySelector(".cart-content");
const productsDOM = document.querySelector(`.products`);

let cart = []; // Cart array
let buttonsDOM = []; // Button array


// Object info
let itemObject = [{
    title: "Chocolate",
    price: 10.99,
    id: 1,
    img: "https://images.pexels.com/photos/1055272/pexels-photo-1055272.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Cream",
    price: 12.99,
    id: 2,
    img: "https://images.pexels.com/photos/1055270/pexels-photo-1055270.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
}, {
    title: "Frosting",
    price: 12.99,
    id: 3,
    img: "https://images.pexels.com/photos/1055271/pexels-photo-1055271.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Berry",
    price: 14.99,
    id: 4,
    img: "https://images.pexels.com/photos/3081657/pexels-photo-3081657.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Deluxe",
    price: 19.99,
    id: 5,
    img: "https://images.pexels.com/photos/1998634/pexels-photo-1998634.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}, {
    title: "Oreo",
    price: 14.99,
    id: 6,
    img: "https://images.pexels.com/photos/783274/pexels-photo-783274.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"
}];


// Open the cart on click
cartBtn.addEventListener(`click`, () => {
    cartOverlay.classList.remove(`invisible`);
});

// Hide cart overlay
function hideOverlay() {
    cartOverlay.classList.add(`invisible`);
    // cartOverlay.classList.remove(`invisible`);
}

// Close cart on click
closeCartBtn.addEventListener(`click`, () => {
    cartOverlay.classList.add(`invisible`);
});

// Remove all items from the cart and hide the overlay
clearCartBtn.addEventListener(`click`, hideOverlay);

// Delete item from cart
function deleteSingleItem(id) {
    console.log(`Deleted single item`);
    items = items.filter(itemObject.id !== id);
}

// Delete all items from cart
function deleteAllItems(id) {
    console.log(`Deleted all items`);
}

// Display products
function displayProducts() {
    let html = ``;
    itemObject.forEach((item) => {
        html += `
        <div class="bg-white rounded-lg">
            <img class="rounded-md w-screen object-cover max-h-60"
                src="${item.img}"
                alt="">
            <div class="py-2 px-8 text-gray-600">
                <div class="grid grid-cols-2 py-3 text-xl font-bold ">
                    <h3>${item.title}</h3>
                    <p class="text-right">$${item.price}</p>
                </div>
                <button data-id=${item.id}
                    class="bg-purple-200 font-bold px-3 mt-2 text-xl py-4 mb-4 w-full rounded-md transition-all hover:bg-purple-300 bag-btn">Purchase</button>
            </div>
        </div>
        `;
    });
    productsDOM.innerHTML = html;
}

// Loop through buttons to fetch ID
function addProductsToCart() {
    const buttons = [...document.querySelectorAll(`.bag-btn`)];
    buttonsDOM = buttons;
    buttons.forEach(button => { // loop through the dataset
        let id = button.dataset.id;
        let inCart = cart.find(item => item.id === id);
        if (inCart) {
            button.innerText = "In Cart";
            button.disabled = true;
        }

        function addCartItem() {
            const div = document.createElement('div');
            div.classList.add('cart-item');
            itemObject.forEach((item) => {
                div.innerHTML = `
                <div class="grid align-middle grid-cols-3 gap-2 my-4">
                <img class="h-28 w-28" src="${item.img}" alt="Product"/>
                    <div>
                        <h4>${item.title}</h4>
                        <h5>$${item.price}</h5>
                        <span class="text-red-200" data-id=${item.id}>Remove</span>
                    </div>
                    <div>
                        <i class="fas fa-chevron-up text-red-200 align-middle" data-id=${item.id}></i>
                        <p class="align-middle item-amount">${item.amount}</p>
                        <i class="fas fa-chevron-down text-red-200 align-middle data-id=${item.id}"></i>
                    </div>
                </div>`;
            });
            cartContent.appendChild(div);
        }

        // Disable button when clicked
        button.addEventListener(`click`, event => {
            event.target.innerText = "In Cart";
            event.target.disabled = true;
            console.log(event.target.dataset);
            addCartItem();
        });
    });
}

displayProducts();
addProductsToCart();

Answer

Two problems here, your addCartItem function was inside a loop of the buttons array, and addCartItem should select and itemObject when looping though.

Quick fix, please note the itemObject.filter(itm => itm.id === parseInt(selectedID) ) and selectedID passed to addCartItem:

    // Loop through buttons to fetch ID
    function addProductsToCart() {
        const buttons = [...document.querySelectorAll(`.bag-btn`)];
        buttonsDOM = buttons;
        function addCartItem(selectedID) {
            const div = document.createElement('div');
            div.classList.add('cart-item');
            itemObject.filter(itm => itm.id === parseInt(selectedID) ).forEach((item) => {
                div.innerHTML = `
                <div class="grid align-middle grid-cols-3 gap-2 my-4">
                <img class="h-28 w-28" src="${item.img}" alt="Product"/>
                    <div>
                        <h4>${item.title}</h4>
                        <h5>$${item.price}</h5>
                        <span class="text-red-200" data-id=${item.id}>Remove</span>
                    </div>
                    <div>
                        <i class="fas fa-chevron-up text-red-200 align-middle" data-id=${item.id}></i>
                        <p class="align-middle item-amount">${item.amount}</p>
                        <i class="fas fa-chevron-down text-red-200 align-middle data-id=${item.id}"></i>
                    </div>
                </div>`;
            });
            cartContent.appendChild(div);
        }

        buttons.forEach(button => { // loop through the dataset
            let id = button.dataset.id;
            let inCart = cart.find(item => item.id === id);
            if (inCart) {
                button.innerText = "In Cart";
                button.disabled = true;
            }


            // Disable button when clicked
            button.addEventListener(`click`, event => {
                console.log(event.target);
                event.target.innerText = "In Cart";
                event.target.disabled = true;
                console.log(event.target.dataset);
                addCartItem(event.target.dataset.id);
            });
        });
    }