unitSphere
unitSphere

Reputation: 311

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);
    }
}```

Upvotes: 1

Views: 1330

Answers (1)

Abdelrahman Gobarah
Abdelrahman Gobarah

Reputation: 1589

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>

Upvotes: 6

Related Questions