Ed Angelis Ribeiro
Ed Angelis Ribeiro

Reputation: 109

How to replicate HTML elements with Loop in javascript

I'm trying to replicate html elements with a javascript for loop, the loop runs fine but does not create new elements in html.

When i print father in console, Continued with 1 element only.

var child = document.getElementById('child');
var father = document.getElementById('father');

for (let i = 0; i < 4; i++) {
  father.appendChild(child)
}
<div id="father">
  <div id="child" class="row mt-5">
    <div class="col-sm-8">
      <h2 class="news" id="">News</h2>
    </div>
  </div>
</div>

I want print div child 5 times in the browser

Upvotes: 1

Views: 1045

Answers (3)

behzad besharati
behzad besharati

Reputation: 6910

You can also use template tag for cloning, the template tag is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.

var father = document.getElementById('father');
var temp = document.getElementsByTagName("template")[0];
  
for (let i = 0; i < 4; i++) {
   father.appendChild(temp.content.cloneNode(true))
}
  <template>
  
    <div class="row mt-5">
        <div class="col-sm-8">
            <h2 class="news" id="">News</h2>
        </div>
    </div>

  </template>
  
  <div id="father">

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44107

Try using cloneNode:

var child = document.getElementById('child');
var father = document.getElementById('father');

for (let i = 0; i < 4; i++) {
    let childCopy = child.cloneNode(true);
    father.appendChild(childCopy);
}
<div id="father">
    <div id="child" class="row mt-5">
        <div class="col-sm-8">
            <h2 class="news" id="">News</h2>
        </div>
    </div>
</div>

Upvotes: 4

holydragon
holydragon

Reputation: 6728

Use .cloneNode

var child = document.getElementById('child');
var father = document.getElementById('father');

for (let i = 0; i < 4; i++) {
  father.appendChild(child.cloneNode(true))
}
<div id="father">
  <div id="child" class="row mt-5">
    <div class="col-sm-8">
      <h2 class="news" id="">News</h2>
    </div>
  </div>
</div>

Upvotes: 4

Related Questions