Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Cloning and inserting elements, part 2
We inserted the template, and after that we inserted another element. And again we tried to insert the template. As a result, the template only appeared by itself at the end of the list. Why did this happen?
Because there is only one element, even if it is a template. We cannot insert one element several times in different places on the same page. After all, we can’t be in several places at the same time, can we? So DOM elements can’t either.
Therefore, that is why we clone DOM elements. We can clone any elements, including templates, and insert these copies on the page as many times as we like.
First, let’s see how cloning works. To do this, you can use the append
method. It returns a cloned element.
Please note that this method has an argument that is a Boolean value. However, if you pass the value false
, then the element itself with its classes and attributes will be cloned, but any child elements will be excluded.
element.cloneNode(false); // Returns the cloned element without any nested elements.
Try to clone an element, pass the argument false
to the cloneNode
, and insert this element on the page.
In the next assignment we will learn what happens if we pass the true
argument or even no arguments at all to cloneNode
. Spoiler: Everything is all quite strange.
- index.html
- style.css
- script.js
Thanks! We’ll fix everything at once!
Comments