Cloning HTML elements

Do you have any idea of code reusability in HTML that may help you create an object or a set of objects as need by creating a replica/clone of an existing object?

You can do that using a JavaScript function i.e. cloneNode().


var clone_obj=node.cloneNode(true/false);

The parameter is either true or false depending on your need of the child-nodes of the node object. if true the node will be cloned along with all its child-nodes otherwise if false then the child-nodes will not be replicated.


<div id=div1 style="border:5px solid green" onClick="alert(">hi
<div id=div2 style="border:2px solid yellow">hello</div>
<div id=div3 style="border:2px solid red">world</div>
<button onClick="document.body.appendChild(document.getElementById('div1').cloneNode(true));">cloneNode</button>

Check this DEMO for a better idea about its usage.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s