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

Time:01-17

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" ></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" >
  <div id="result0"></div>
  <div id="result1"></div>
  <div id="result2"></div>
<div>

but for me it does nothing

CodePudding user response:

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

  • Related