1

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.

1 Answer 1

1

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.

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

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.