Latest web development tutorials
 

HTML DOM cloneNode() Method

< Element Object

Example

Copy a <li> element from one list to another:

// Get the last <li> element ("Milk") of <ul> with id="myList2"
var itm = document.getElementById("myList2").lastChild;

// Copy the <li> element and its child nodes
var cln = itm.cloneNode(true);

// Append the cloned <li> element to <ul> with id="myList1"
document.getElementById("myList1").appendChild(cln);

Before cloning:

  • Coffee
  • Tea
  • Water
  • Milk

After cloning:

  • Coffee
  • Tea
  • Milk
  • Water
  • Milk
Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The cloneNode() method creates a copy of a node, and returns the clone.

The cloneNode() method clones all attributes and their values.

Tip: Use the appendChild() or insertBefore() method to insert the cloned node to the document.

Tip: Set the deep parameter value to true if you want to clone all descendants (children), otherwise false.


Browser Support

Method
cloneNode() Yes Yes Yes Yes Yes

Syntax

node.cloneNode(deep)

Parameter Values

Parameter Type Description
deep Boolean Optional. Specifies whether all descendants of the node should be cloned.
  • true - Clone the node, its attributes, and its descendants
  • false - Default. Clone only the node and its attributes

Technical Details

Return Value: A Node object, representing the cloned node
DOM Version Core Level 1 Node Object

Examples

More Examples

Example

Copy a <div> element, including all its attributes and child elements, and append it to the document:

var elmnt = document.getElementsByTagName("DIV")[0];
var cln = elmnt.cloneNode(true);
document.body.appendChild(cln);
Try it Yourself »

Related Pages

HTML DOM reference: href="met_document_adoptnode.html">document.adoptNode() Method

HTML DOM reference: href="met_document_importnode.html">document.importNode() Method

HTML DOM reference: href="met_document_createelement.html">document.createElement() Method

HTML DOM reference: href="met_document_createtextnode.html">document.createTextNode() Method


< Element Object