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!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK TUTORIAL

 

TABLE OF CONTENTS

Download & Notes Clone Elements Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

WAYS TO DUPLICATE ELEMENTS

All right, let us now get into the various ways on how to clone HTML elements in Javascript.

 

METHOD 1) CLONE NODE

1-clone-node.html
<!-- (A) THE ORIGINAL, TO BE COPIED -->
<div id="source">
  <h1>Hello World!</h1>
  <p>My name na Uvuvwevwevwe Onyetenyevwe Ugwemubwem Ossas.</p>
</div>

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

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

// (C2) CREATE & APPEND EVIL CLONE
let evilclone = source.cloneNode(true);
evilclone.removeAttribute("id");
destination.appendChild(evilclone);
</script>

This one should be very straightforward.

  • Grab the source element – var source = document.getElementById("source")
  • Create an evil clone – let evilclone = source.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.
    • The clone will also share the same id. Do be extra careful, remove or replace the id for the clone.
  • Then append it to the destination – destination.appendChild(evilclone)

 

 

METHOD 2) INNER HTML

2-inner.html
<!-- (A) THE ORIGINAL, TO BE COPIED -->
<div id="source">
  <h1>Hello World!</h1>
  <p>My name na Uvuvwevwevwe Onyetenyevwe Ugwemubwem Ossas.</p>
</div>

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

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

// (C2) CREATE & APPEND EVIL CLONE 
let evilclone = source.innerHTML;
destination.innerHTML = evilclone;
</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 destination – destination.innerHTML = source.innerHTML.

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

 

METHOD 3) OUTER HTML

3-outer.html
<!-- (A) THE ORIGINAL, TO BE COPIED -->
<div id="source">
  <h1>Hello World!</h1>
  <p>My name na Uvuvwevwevwe Onyetenyevwe Ugwemubwem Ossas.</p>
</div>

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

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

// (C2) CREATE & APPEND EVIL CLONE 
let evilclone = source.outerHTML;
evilclone = evilclone.replace(' id="source"', "");
destination.innerHTML = evilclone;
</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 THE SOURCE + DESTINATION
var source = document.getElementById("source"),
    destination = document.getElementById("destination");
 
// (C2) APPEND ROWS BY CLONING THE TEMPLATE
for (let i=1; i<=5; i++) {
  let clonerow = document.importNode(source.content, true);
  let clonecells = clonerow.querySelectorAll("td");
  clonecells[0].innerHTML = "Cloned row" + i;
  clonecells[1].innerHTML = "HI!";
  destination.appendChild(clonerow);
}
</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().

 

 

USEFUL 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 *