JavaScript’s Node.cloneNode()
method returns a duplicate of the Node
. Its optional parameter controls whether the subtree contained in the Node
is also cloned or not.
Syntax
Node.cloneNode();
Node.cloneNode(parameter);
Parameters
An optional Boolean value specifying whether the subtree contained in the node is cloned or not.
The parameter defaults to false
.
Examples
Here are some examples of using the JavaScript cloneNode()
method.
Suppose we have the following HTML elements:
<p id="paragraph"><span>Announcement:</span> Today, the JavaScript Guide has a special offer.</p>
We would like to clone the p
element. What should we do?
Let’s consider our options. One obvious way is to select the element with the getElementById()
method and use the cloneNode()
method:
let paragraph = document.getElementById('paragraph');
let clone = paragraph.cloneNode();
Now we have the element duplicated and stored in the clone
variable. However, if we log the duplicate to the console, all we can see is an empty p
element:
console.log(clone);
// <p id="paragraph"></p>
That is because we did not clone the subtree contained in the node. Had we cloned the subtree, the results would have been different:
let paragraph = document.getElementById('paragraph');
let clone = paragraph.cloneNode(true);
console.log(clone);
// <p id="paragraph"><span>Announcement:</span> Today, the JavaScript Guide has a special offer.</p>
Additional notes
As you can see, using the cloneNode()
method led to duplicate id
attributes in our document: We have the original p
element whose id
is “paragraph” and we have the cloned element with the same id
. Since id
attributes should be unique, one of them should be changed. We can change the id
of the cloned element like this:
clone.id = "newParagraph";
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
cloneNode() |
1 | 12 | 1 | 6 | 7 | 1.1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 |