javascript - 如何在 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,这可能是问题吗?
解决方案
要设置这些元素的样式,有两种方法:
将内联 CSS 添加到元素本身。
phone.style.color = 'blue';
向元素添加一些 ID 或类,然后引用它们
phone.className += "my-element";
.my-element {color: blue;}
推荐阅读
- excel - VBA中的双For循环,不同的下标
- c# - c#为列表包含构建通用表达式树
- mysql - 在mysql查询中使用,在concat函数中分隔
- sapui5 - 在 SAP Fiori 启动板中多次显示单个应用程序磁贴
- python - 为什么这个循环不起作用,而类似的循环起作用?
- javascript - 使用 javascript 创建嵌入在表单中的元素
- leaflet - 图层控制:链接两个叠加层,移除叠加层 A 也会移除叠加层 B
- javascript - 启用要在 Bot 的弹出窗口中打开的链接
- java - Java:具有 ThreadPool 和 CountDownLatch 的 Dijkstra 算法导致越界异常
- java - 使用 fcm 进行通知时,onMessageReceived(RemoteMessage remoteMessage) firebase chat null 错误