Search code examples
htmlinnerhtmlgetelementbyid

Printing value of iterator in dynamic div


I have created a dynamic div which is rendered 19 times. I want to print the ID of iterator (i) in inner html dynamic Div. Can anyone please help me. Below is my code

var d1 = document.getElementById("div1");
for (var i = 0; i < 20; i++) {
  d1.innerHTML += '<div class="box">Print i here</div>';
}
<h2>My Loop Printing Divs</h2>
<div id="div1"></div>


Solution

  • You can use variable directly like:

    var d1 = document.getElementById("div1");
    for (var i = 0; i < 20; i++) {
      d1.innerHTML += '<div class="box">Print ' + i + ' here</div>';
    }
    <h2>My Loop Printing Divs</h2>
    <div id="div1"></div>