2

I have a side drawer where I'm showing the current cart products selected by the user. Initially, I have a <p> tag saying the cart is empty. However, I want to remove it if the cart has items inside. I'm using an OOP approach to design this page. See below the class I'm working with.

I tried to use an if statement to condition the <p> tag but this seems the wrong approach. Anyone has a better way to do this. See screenshot of the cart in the UI and code below:

Without cart item

with item

class SideCartDrawer {
    cartProducts = [];

    constructor() {
        this.productInCartEl = document.getElementById('item-cart-template');
    }

    addToCart(product) {
        const updatedProducts = [...this.cartProducts];
        updatedProducts.push(product);
        this.cartProducts = updatedProducts;
        this.renderCart();
    }

    renderCart() {
        const cartListHook = document.getElementById('cart-items-list');
        let cartEl = null;
        if (this.cartProducts.length === 0) {
            cartEl = '<h2>You Cart is Empty</h2>';
        } else {
            const productInCartElTemplate = document.importNode(
                this.productInCartEl.content,
                true
            );
            cartEl = productInCartElTemplate.querySelector('.cart-item');
            for (let productInCart of this.cartProducts) {
                cartEl.querySelector('h3').textContent = productInCart.productName;
                cartEl.querySelector('p').textContent = `£ ${productInCart.price}`;
                cartEl.querySelector('span').textContent = 1;
            }
        }
        cartListHook.append(cartEl);
    }
}

By the way, the <p> should reappear if the cart is back to empty :) !

doo_doo_fart_man
  • 394
  • 3
  • 11
Carlos Escobar
  • 422
  • 3
  • 15

1 Answers1

1

With how your code is setup, you would want to reset the list on each render. You would do this by totally clearing out #cart-items-list. Here is a deletion method from this question

while (cartListHook.firstChild) {
  cartListHook.removeChild(cartListHook.lastChild);
}

But you could use any method to delete the children of an HTML Node. To reiterate, you would put this right after getting the element by its id.

  • P.S. You probably want to put more code into your for loop, because it seems like it will only create cart-item element even if there are multiple items in this.cartProducts.