Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Cloning and inserting elements, part 1
We saved the template for future assignments. All that remains to be done is to apply this template to our code so that we can design the new task based on it. In order to do this, let’s put aside our to-do list for the moment and examine another DOM API method.
You can’t just take a single element and add it multiple times to the page. It can only be inserted once.
Let’s make sure of this by taking a look at an example.
Let’s bring up a block with product listings. The template for the product listing is stored in the template
tag.
<body>
…
<template id="element-template">
<div class="el">
<span></span>
</div>
</template>
</body>
The template has only been inserted in the page once. This code has already been written. Let’s try to insert the same template on the page again.
To insert elements into the page, we will use the appendChild
method. It adds the specified elements to the end of the parent block. We already worked with this method here.
In the code, you can discover a call to a child element in the template using the element.children[0]
.
This is the normal approach for our case. The layout will not change for the next four tasks, and we know for sure that we need the first child element. And since children
is a collection that is similar to an array, we can call the first child element by index.
- index.html
- style.css
- script.js
Thanks! We’ll fix everything at once!
Click inside the mini browser to put the focus in this window.
Comments