首页 > 解决方案 > javascript中的dom操作和获取

问题描述

我正在尝试使用 fetch 从 api 获取数据,循环通过数据并将它们呈现为动态创建 html 元素和属性。这是我的代码


    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)
                })

            }

    })

当我运行 JavaScript 文件时,我的控制台中出现错误

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

不知道做错了什么。

标签: javascripthtmlarraysdomdom-manipulation

解决方案


你需要获取元素,因为所有这个函数都返回元素数组

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

在所有其他情况下也是第一个元素或循环集合


推荐阅读