To clone an element, you use the cloneNode()
method of the element that you want to clone:
const target = document.querySelector('div');
const clonedTarget = target.cloneNode();
Code language: JavaScript (javascript)
By default, the cloneNode()
method only clones the target element, but not all descendants of the target element.
To clone the element and also its descendants, you pass true
into the cloneNode()
method:
const target = document.querySelector('div');
const clonedTarget = target.cloneNode(true);
Code language: JavaScript (javascript)
This way of cloning an element is known as the deep cloning.
Was this tutorial helpful ?