0

I am trying to make my shopcart page functional, I am new to this so I am watching youtube and trying to find answers on the internet, but I cant seem to figure out why this problem occures. I managed to get most of the work done, but I am not succeeding at adding items to my shopping cart. (I can only use HTML, CSS and a the basics of JavaScript)

here is my JavaScript code:

function addToCartClicked(event){
    var button = event.target;
    var shopItem = button.parentElement.parentElement
    var title = shopItem.getElementsByClassName("shop-item-title")[0].innerText;
    var price = shopItem.getElementsByClassName("shop-item-price")[0].innerText;
    var imageSrc = shopItem.querySelector("#BigImg")
    console.log(title, price, imageSrc)
    addItemToCart(title, price, imageSrc)
}

function addItemToCart(title, price, imageSrc) {
    var cartRow = document.createElement("div");
    
    var cartItems = document.getElementsByClassName("cart-items")[0]
    var cartRowContents = ` <div class="cart-row">
        <div class="cart-item cart-column">
            <img class="cart-item-image" src="${imageSrc}" width="100" height="100">
            <span class="cart-item-title">${title}</span>
        </div>
        <span class="cart-price cart-column">${price}</span>
        <div class="cart-quantity cart-column">
            <input class="cart-quantity-input" type="number" value="2">
            <button class="btn btn-danger" type="button">REMOVE</button>
        </div>
    </div> `
    cartRow.innerHTML = cartRowContents

    cartItems.append(cartRow)
 ``

and here are the errors I am getting: 
Uncaught TypeError: Cannot read property 'append' of undefined
    at addItemToCart (script.js:99)
    at HTMLButtonElement.addToCartClicked (script.js:79)
addItemToCart @ script.js:99
addToCartClicked @ script.js:79

in what world is property 'append' is undefined? I have a full HTML code in there. 
__________________________________________________________
[object%20HTMLImageElement]:1 GET http://127.0.0.1:5500/products/fancy%20earphones/[object%20HTMLImageElement] 404 (Not Found)
Image (async)
addItemToCart @ script.js:97
addToCartClicked @ script.js:79
Leo
  • 11
  • 3
  • Try appendChild – cfprabhu Aug 29 '21 at 13:03
  • If you using jquery you can use the append – cfprabhu Aug 29 '21 at 13:04
  • As the name of the variable already suggests: `cartItems` is a _collection of elements_. `.append()` is a method of a `Element` and not `HTMLCollection` – Andreas Aug 29 '21 at 13:09
  • I changed it to "var cartItems = document.getElementsByClassName("cart-items")[0]" it didnt help, now I am getting another error: Cannot read property 'append' of undefined – Leo Aug 29 '21 at 13:40

0 Answers0