简体   繁体   English

AppendChild 到 Class 的每个元素

[英]AppendChild to each element of Class

I want to append an element to each div of class "actors" but the function that I wrote adds the element only in the last element with class "actors" (there are two of them in my page).我想将一个元素附加到“actors”类的每个 div 中,但是我编写的函数只在最后一个元素中添加了“actors”类的元素(我的页面中有两个)。 Could you help me how to appendChild correctly in JS please?你能帮我如何在 JS 中正确 appendChild 吗?

async function addActor() {
    let actor_name = document.getElementById("actor_name").value;
    let element = document.createElement("p");
    element.innerHTML = `<p>${actor_name}<input id="scriptText" style="width: 40px;" type="text" name="" value="0"></p>`;
    console.log(element);
    let collection = document.getElementsByClassName("actors");


    for(let item of collection){
        await item.appendChild(element);
        console.log(item.innerHTML);
    }
}```

element is passed by reference, so it move in foreach to div1 then div2 , and so on ... element 是通过引用传递的,所以它在 foreach 中移动到div1然后div2 ,依此类推...

create element in foreach loop and it will workforeach loop创建元素,它将起作用

 async function addActor() { let actor_name = document.getElementById("actor_name").value; let collection = document.getElementsByClassName("actors"); for(let item of collection){ let element = document.createElement("p"); element.innerHTML = `<p>${actor_name}<input id="scriptText" style="width: 40px;" type="text" name="" value="0"></p>`; await item.appendChild(element); } }
 <input id="actor_name" /> <button onclick="addActor()">Add</button> <div class="actors">actors 1: </div> <div class="actors">actors 2: </div> <div class="actors">actors 3: </div> <div class="actors">actors 4: </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM