stemon
stemon

Reputation: 661

Get Element and append multiple times Javascript

I need to get an element and append it multiple times inside its parent.

HTML

<main>
      <div class="wrapper">
        <img src="https://placeimg.com/300/300/arch?t=1493746896324/" />
        <div class="cover"></div>
      </div>
</main>

JS

const main = document.querySelector("main");
const wrapper = document.querySelector(".wrapper");

for (let index = 0; index < 10; index++) {
  main.innerHTML += wrapper;
}

RESULT

[object HTMLDivElement] is inserted instead.

Upvotes: 1

Views: 252

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206342

Cloning a Node

const main = document.querySelector("main");
const wrapper = document.querySelector(".wrapper");

for (let index = 0; index < 10; index++) {
  main.append(wrapper.cloneNode(true));
}
<main>
  <div class="wrapper">
    <img src="https://placeimg.com/300/300/arch?t=1493746896324/" />
    <div class="cover"></div>
  </div>
</main>

Concatenate using outerHTML

Otherwise, given innerHTML and manipulating Strings you could do:

const main = document.querySelector("main");
const wrapper = document.querySelector(".wrapper");

for (let index = 0; index < 10; index++) {
  main.innerHTML += wrapper.outerHTML;
}
<main>
  <div class="wrapper">
    <img src="https://placeimg.com/300/300/arch?t=1493746896324/" />
    <div class="cover"></div>
  </div>
</main>

Pros Cons

Both the above results will end up in the same markup

<main>
  <div class="wrapper">...</div>
  ......
  <div class="wrapper">...</div>
</main>

with the only difference that by using cloning with true, every originally assigned listeners or data will be cloned as well; whilst using concatenation += with .outerHTML() is basically a simple HTML markup concatenation with not much other benefits.

Upvotes: 1

Related Questions