4 Ways To Duplicate HTML Elements In Javascript (Simple Examples)

Welcome to a tutorial on how to duplicate HTML elements. So you are working on a project that requires the creation of evil clones, probably to ease tasks like creating table rows and list items?

An easy way to duplicate an HTML element in Javascript is to use the cloneNode() function:

  • var original = document.getElementById("ID");
  • var clone = original.cloneNode(true);
  • clone.removeAttribute("id");
  • document.getElementById("ID").appendChild(clone);

But there are more mechanisms in Javascript that we can use to clone elements. Just how exactly does each one work? Let us walk through some examples – Read on to find out!

 

 

TLDR – QUICK TUTORIAL

[web_stories_embed url=”https://code-boxx.com/web-stories/duplicate-html-elements-in-javascript/” title=”Duplicate HTML Elements In Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

JAVASCRIPT DUPLICATE HTML ELEMENTS

All right, let us now get into the various ways of cloning HTML elements in Javascript.

 

METHOD 1) CLONE NODE

1-clone-node.html
<!-- (A) THE ORIGINAL -->
<div id="source">
  <h1>TITLE</h1>
  <p>TEXT</p>
</div>

<!-- (B) INSERT CLONE HERE -->
<div id="destination"></div>

<!-- (C) JAVASCRIPT -->
<script>
// (C1) GET THE SOURCE & DESTINATION ELEMENTS
var s = document.getElementById("source"),
    d = document.getElementById("destination");

// (C2) CREATE & APPEND EVIL CLONE
var clone = s.cloneNode(true);
clone.removeAttribute("id");
d.appendChild(clone);
</script>

This one should be very straightforward.

  • Grab the source element – var s = document.getElementById("source")
  • Create an evil clone – let clone = s.cloneNode(true).
    • Take note of the true parameter here, this is to specify “also clone the children enclosed within”. By default, this is false and the children will be excluded from the cloning vat.
    • Do be extra careful, the clone will also share the same id. Remember to remove or replace the id for the clone.
  • Lastly, append the clone to the destination – d.appendChild(clone)

 

 

METHOD 2) INNER HTML

2-inner.html
<!-- (A) THE ORIGINAL -->
<div id="source">
  <h1>TITLE</h1>
  <p>TEXT</p>
</div>

<!-- (B) CLONE TO BE PLACED HERE -->
<div id="destination"></div>

<!-- (B) INSERT CLONE HERE -->
<script>
// (C1) GET SOURCE & DESTINATION ELEMENTS
var s = document.getElementById("source"),
    d = document.getElementById("destination");

// (C2) CREATE & APPEND EVIL CLONE 
let clone = s.innerHTML;
d.innerHTML = clone;
</script>

This is pretty much the same steps as above, just a different “cloning method”.

  • Get the source and destination elements – document.getElementById("source"), document.getElementById("destination").
  • Simply copy the HTML from the source to the destination – d.innerHTML = s.innerHTML.

That’s all, but take note that innerHTML will only include the “internal HTML”, exclusive of the tag itself. I.E. s.innerHTML is exclusive of <div id="source"> itself.

 

METHOD 3) OUTER HTML

3-outer.html
<!-- (A) THE ORIGINAL -->
<div id="source">
  <h1>TITLE</h1>
  <p>TEXT</p>
</div>

<!-- (B) INSERT CLONE HERE -->
<div id="destination"></div>

<!-- (C) JAVASCRIPT -->
<script>
// (C1) GET SOURCE & DESTINATION ELEMENTS
var s = document.getElementById("source"),
    d = document.getElementById("destination");

// (C2) CREATE & APPEND EVIL CLONE 
let clone = s.outerHTML;
clone = clone.replace(' id="source"', "");
d.innerHTML = clone;
</script>

Yep… This should be Captain Obvious now – outerHTML also includes the <div id="source"> element itself.

 

 

METHOD 4) CLONING FROM A TEMPLATE

4-template.html
<!-- (A) SOURCE TEMPLATE -->
<template id="source">
  <tr>
    <td class="cellA"></td>
    <td class="cellB"></td>
  </tr>
</template>

<!-- (B) DESTINATION TABLE -->
<table id="destination">
  <tr>
    <td class="cellA">Foo</td>
    <td class="cellB">Bar</td>
  </tr>
</table>

<!-- (C) JAVASCRIPT -->
<script>
// (C1) GET SOURCE + DESTINATION
var s = document.getElementById("source"),
    d = document.getElementById("destination");
 
// (C2) APPEND ROWS BY CLONING THE TEMPLATE
for (let i=1; i<=5; i++) {
  let row = document.importNode(s.content, true);
  let cells = row.querySelectorAll("td");
  cells[0].innerHTML = "Cloned row" + i;
  cells[1].innerHTML = "HI!";
  d.appendChild(row);
}
</script>

This is probably one that not many people know about. Yes, there is a legit HTML <template> tag, and it comes in very handy in appending things like table rows plus list items. But please take note that handling the <template> tag is slightly different. We are using importNode() here to handle the cloning instead of the “usual” cloneNode().

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

WHICH IS THE BETTER METHOD?

Well, it really depends on the situation. Personally, I am pretty much stuck to using innerHTML as a beginner, thinking that it is convenient and easy to understand without all that object-oriented madness.

It was only later that I realized the line of thought is very wrong. As demonstrated above, the “object-oriented way” of cloning a template can be very handy in appending new rows and items quickly; Using innerHTML would have been a mess otherwise, having to manually type out all the HTML code as a string.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

How To Clone HTML Elements In Javascript (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *