1

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

2
  • Possible duplicate of How to insert the same html element twice? Commented Feb 7, 2019 at 8:06
  • (FYI, when someone formats your code and creates a snippet, please don't sabotage it again.) Commented Feb 7, 2019 at 8:09

3 Answers 3

4

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>

Sign up to request clarification or add additional context in comments.

Comments

4

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>

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.