javascripthtmldomappendchildcreateelement

Append an existing <DIV> with a child DIV using a new ID for each item in an array


I'm trying to loop through an array and add a div for each item of the array with a numbered ID correlating to the item's index of the array. This ID would be later used to add further content to the newly generated child divs.

My code:

HTML

<div id="resultsBox" class="results"></div>

JavaScript

var resultsArr = [apple, orange, banana]

for (var i = 0; i < resultsArr.length; i++) {
  var resultDiv = document.createElement("div")
  resultDiv.setAttribute(id, "result" + i)
  resultsBox.appendChild(resultDiv) 
}

I would expect that this would change the HTML to:

<div id="resultsBox" class="results">
  <div id="result0"></div>
  <div id="result1"></div>
  <div id="result2"></div>
<div>

but for me it does nothing


Solution

  • var resultsArr = ['apple', 'orange', 'banana'];
    var resultsBox = document.getElementById('resultsBox');
    
    for (var i = 0; i < resultsArr.length; i++) {
      var resultDiv = document.createElement("div");
      resultDiv.id = "result" + i;
      resultDiv.innerHTML = resultsArr[i]; // just to see the div.
      resultsBox.appendChild(resultDiv);
    }
    <div id="resultsBox" class="results"></div>

    The problem that you had was using the setAttribute function. It won't work well with id. This is mainly because the id is a property and not an attribute.