Search code examples
javascriptappendappendchild

forEach loop keeps appending to first child element only


I'm in a bit of a pickle. I'm running a forEach loop for an API that will create a new div for each result with some html appended inside it. While the data is being retrieved, it appends only to the first div created. I'm trying to ensure each set of text ends up in each individual div. Can anyone enlighten me on what I'm doing wrong?

app.displayResults = (arrayOfObjects) => {
  arrayOfObjects.forEach((Object) =>{
    
    const number = Object.house_number;
    const address = Object.street_name;
    const zipCode = Object.zip_code;
    const borough = Object.borough;
    const date = Object.inspection_date;
    const initial = Object.inspection_type;
    const iResult = Object.result;
  
    const resultContainer = document.createElement("div");
    resultContainer.classList.add('resultContainer');
    document.querySelector('.inspectionResults').append(resultContainer); 
    
    const innerHTML = `
    <p class = "recordDetails"> ADDRESS: ${number}${address}</p>
    <p class = "recordDetails"> DATE: ${date}</p>
    <p class = "recordDetails"> BOROUGH: ${borough}</p>`

    const record = document.createElement("div");
    record.classList.add('record');
    record.innerHTML = `${innerHTML}`

    document.querySelector(".resultContainer").append(record)
  })
}


Solution

  • In the last line of your forEach callback, you're querying the first .resultContainer element instead of the one you've created before. Instead of immediately appending that div to the DOM, append your record to resultContainer, then append only resultContainer to the DOM, like this (I've changed Object to obj because Object is already defined):

    app.displayResults = (arrayOfObjects) => {
      arrayOfObjects.forEach((obj) =>{
        const number = obj.house_number;
        const address = obj.street_name;
        const zipCode = obj.zip_code;
        const borough = obj.borough;
        const date = obj.inspection_date;
        const initial = obj.inspection_type;
        const iResult = obj.result;
      
        const resultContainer = document.createElement("div");
        resultContainer.classList.add('resultContainer');
        
        const innerHTML = `
        <p class = "recordDetails"> ADDRESS: ${number}${address}</p>
        <p class = "recordDetails"> DATE: ${date}</p>
        <p class = "recordDetails"> BOROUGH: ${borough}</p>`
    
        const record = document.createElement("div");
        record.classList.add('record');
        record.innerHTML = `${innerHTML}`
    
        resultContainer.appendChild(record); // instead of directly appending record to document append it to the container, then append the container to the document
        document.querySelector('.inspectionResults').append(resultContainer); 
      })
    }