首页 > 解决方案 > 如何在 CSS 中引用 document.createElement

问题描述

我正在从 API 中选择数据,然后使用 document.createElement 将其制成对象,但我该如何设置它们的样式?

这是我的JS代码:

  fetch('https://randomuser.me/api/?results=5&nat=us').then(response =>{
        return response.json();
    }).then(responseJson=>{
        responseJson.results
        console.log(responseJson);

        for(const user of responseJson.results){
            const img = document.createElement ("IMG");
            img.innertext = user.picture.medium;
            img.setAttribute("src", user.picture.medium)
            img.setAttribute("width", "50");
            img.setAttribute("height", "50");
            img.setAttribute("alt", "");
            document.body.appendChild(img)

            const name = document.createElement("SPAN");
            name.innerText = user.name.first;
            document.body.appendChild(name);

            const phone = document.createElement("SPAN");
            phone.innerText = user.phone;
            document.body.appendChild(phone);

            console.log(user);
        }
    })

我试图引用 name.innerText 但这也不起作用。但是我可以通过调用来引用它们,例如:

span {
 color: blue;
}

当我检查代码时,它显示它创建的跨度没有任何 id,这可能是问题吗?

标签: javascripthtmlcss

解决方案


要设置这些元素的样式,有两种方法:

  1. 将内联 CSS 添加到元素本身。

    phone.style.color = 'blue';

  2. 向元素添加一些 ID 或类,然后引用它们

    phone.className += "my-element";

    .my-element {color: blue;}


推荐阅读