简体   繁体   中英

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). Could you help me how to appendChild correctly in JS please?

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 ...

create element in foreach loop and it will work

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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