Cloning HTML Element using HTML DOM cloneNode Method

Cloning HTML Elements is possible. HTML DOM cloneNode Method is used to make copies of HTML Elements. With this method you can make more then one clones of HTML Element.

How To Make a Clone of HTML Element

One way to make a clone of HTML Element is to use HTML DOM cloneNode method. This method creates a copy or clone of the node or element and returns the clone. The clone method also clones the attributes of HTML element and their values.

Watch our Video Tutorial given below to see how to make a clone of HTML element.

Code To Make a Clone of HTML Element

In the HTML section I have created a Div Element with an Id. Using this Id I have made clones of this Div Element.

<!DOCTYPE html>
<html>
<body>
<div id='div'></div>
</body>
</html>

Then using the cloneNode method the clone of Div Element is created. The code is given below.

<!DOCTYPE html>
<html>
<body>
<script>
  var element= document.getElementById("div");
    var clone = element.cloneNode(true);
    clone.id="div1"
    element.after(clone);
</script>
</body>
</html>

As you can see the id of clone element is set to 'div1'

Make Multiple Clones of HTML Element

Now to make multiple clones or copies of HTML Element same code is used inside the while loop. Look at the code.

<!DOCTYPE html>
<html>
<body>
<script>
     var i=1;
        while(i<5)
            {
    var element= document.getElementById("div");
    var clone = element.cloneNode(true);
    clone.id="div"+i;
    element.after(clone);
        i=i+1;        
                }
</script>
</body>
</html>

Demo of HTML DOM cloneNode Method

In the demo, the clone of paragraph HTML element with id 'clone' is created using cloneNode method.

Original Paragraph HTML Element

Clone HTML Element Demo

Clone of Paragraph HTML Element

The second paragraph element that you can see is actually the clone or copy of first one. The after method creates the clone just after the original HTML element in HTML DOM.

Video Tutorial on Cloning HTML Element

Watch this video tutorial to see how to create a clone of HTML Element.