Home > Net >  Apendchild only apending once in ForEach method
Apendchild only apending once in ForEach method

Time:12-02

function addOrgsToCard(Data) { 
  const orgs = document.getElementById("orgs");
  const org = document.createElement("div");
  org.classList.add("org");
  Data.forEach((organisation)=>{
    org.innerHTML = `
    <div >
    <img src="${organisation.avatar_url}" alt="" />
    <span>${organisation.login}</span>
    </div>
  `;
  console.log(organisation.login);
  orgs.appendChild(org);
  });
  
}

This is the function to add organization details in a div of a profile card but the problem is apendchild method is appending only one organisation detail (the last one from the API call) ,Can anyone help me solve this issue?enter image description here

CodePudding user response:

org.innerHTML = overwrites the previous value. So every time you loop over the data the previous elements get removed. You should move the creation of your org element inside the forEach loop:

function addOrgsToCard(Data) { 
  const orgs = document.getElementById("orgs");
  Data.forEach((organisation)=>{
    const org = document.createElement("div");
    org.classList.add("org");
    org.innerHTML = `
    <div >
    <img src="${organisation.avatar_url}" alt="" />
    <span>${organisation.login}</span>
    </div>
    `;
    console.log(organisation.login);
    orgs.appendChild(org);
  });
}

CodePudding user response:

  1. Try using only "append"(I am not sure if this works).
  • Related