0

i am trying to use fetch to get data from an api, loop thru the data and render them as am dynamically creating the html element and attribute. here is my code


    fetch('https://get_products')
        .then((response) => {
            return response.json();
        })
        .then((item) => {
            data = item.data
            console.log(data)

            if (data && data.length > 0) {
                data.map((item) => {
                    console.log(item)
                    var store = document.getElementsByClassName('Store')
                    var ul = document.createElement("ul").classList.add("ProductGrid")
                    var li = document.createElement("li").classList.add("ProductGrid_item")
                    var a = document.createElement("a")
                    var divCard = document.createElement("div").classList.add("ProductCard")
                    var divImg = document.createElement("div").classList.add("ProductCard_image")
                    var img = document.createElement("img").src = item.photo
                    var divInfo = document.createElement("div").classList.add("ProductCard_info")
                    var h5 = document.createElement("h5").classList.add("ProductCard_name")
                    var name = document.createTextNode(item.name)
                    var p = document.createElement("p").classList.add("ProductCard_price")
                    var price = document.createTextNode(item.proce)

                    store.appendChild(ul)
                    li.appendChild(a)
                    a.appendChild(divCard)
                    divCard.appendChild(divImg)
                    divImg.appendChild(img)
                    divCard.appendChild(divInfo)
                    divInfo.appendChild(h5)
                    divInfo.appendChild(p)
                    p.appendChild(price)
                    h5.appendChild(name)
                })

            }

    })

when i run the JavaScript file am having an error in my console

index.js:76 Uncaught (in promise) TypeError: store.appendChild is not a function
    at index.js:76
    at Array.map (<anonymous>)
    at index.js:60

not sure what am doing wrong.

coder
  • 1
  • 1

1 Answers1

0

you need to get element cause all this function return arrays of elements

var store = document.getElementsByClassName('Store')[0];

in all other cases also 1st element or loop collection

Ivan Smyrnov
  • 339
  • 2
  • 10