HTML DOM cloneNode() Method
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
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.
|
Technical Details
Return Value: | A Node object, representing the cloned node |
---|---|
DOM Version | Core Level 1 Node Object |
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: document.adoptNode() Method
HTML DOM reference: document.importNode() Method
HTML DOM reference: document.createElement() Method
HTML DOM reference: document.createTextNode() Method