JavaScript node.cloneNode() Method

You are Here:

JavaScript node.cloneNode() Method

The node.cloneNode() method creates a copy of a node (including attributes and their values) and returns the clone.

Note: It does not copy event listeners added using addEventListener() or those assigned to element properties.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point">Hello world</p> <script> var x = document.getElementById("point"); var dup = x.cloneNode(true); x.appendChild(dup); </script> </body> </html>

Syntax

node.cloneNode(deep)

Parameter Values

ValueTypeExplanation
deepOptionalIf true, the children of the node should also be cloned.
If false, to clone only the specified node.

Return Values

ValueExplanation
ObjectReturns a duplicate of the node on which this method was called.

Clone Node Only (not text)

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <button onclick="myTrue()">True</button> <button onclick="myFalse()">False</button> <p>I'm paragraph</p> <script> var x = document.getElementsByTagName("p")[0]; function myTrue(){ var dup = x.cloneNode(true); document.body.appendChild(dup); } function myFalse(){ var dup = x.cloneNode(false); //Clone only node, not text var textnode = document.createTextNode("I'm also a paragraph"); dup.appendChild(textnode); document.body.appendChild(dup); } </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author