我無法弄清楚我做錯了什么。
這段代碼作業正常:
pic.forEach(photo => {
const newDiv = document.createElement("div");
newDiv.className = 'photo';
newDiv.innerHTML = `<img src=${photo.urls.small}>`
document.body.appendChild(newDiv);
但我想把這個 newDiv 嵌套在現有的里面,所以我準備了帶有班級照片的 DIV。
const pic = result.results;
pic.forEach(photo => {
const gallery = document.getElementsByClassName('photos');
const newDiv = document.createElement("div");
newDiv.className = 'photo';
newDiv.innerHTML = `<img src=${photo.urls.small}>`
gallery.appendChild(newDiv);
而這個它不起作用。
uj5u.com熱心網友回復:
該函式getElementsByClassName將回傳 an Array、 an HTMLCollectionOf<Element>,這就是為什么直接呼叫appendChild不起作用的原因,在這種情況下您有一些選擇。回圈遍歷所有元素,但似乎只有一個。
const gallery = document.getElementsByClassName('photos')[0];
// Both will get only the first Element that matches
const gallery = document.querySelector('.photos');
現在您可以附加新元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345977.html
標籤:javascript html
上一篇:如何在表格中全選和取消?
下一篇:移動谷歌瀏覽器不發送cookie
