In this lesson, we will learn how to get copies of elements. It will be possible to work with these copies, as with ordinary elements - change them and insert them into the right place on the page. The process of making copies of elements is called cloning.
You can clone an element using the cloneNode
method.
True or false must be passed as a parameter of this method.
If true is passed, then the element is cloned completely,
along with all attributes and child elements, and if false,
only the element itself is cloned.
Let's look at an example. Let's say we have this code:
<div id="parent">
<div class="elem">
<p>first paragraph</p>
<p>second paragraph</p>
</div>
</div>
Make a copy of the block with the elem
class and paste it at the end of the
#parent block:
let parent = document.querySelector('#parent');
let elem = parent.querySelector('.elem');
let clone = elem.cloneNode(true);
parent.appendChild(clone);
The result will be the following:
<div id="parent">
<div class="elem">
<p>first paragraph</p>
<p>second paragraph</p>
</div>
<div class="elem">
<p>first paragraph</p>
<p>second paragraph</p>
</div>
</div>
Given an input. Given a button. Clone this input by pressing the button.