Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
The contents of the <template> tag, document-fragment
If you expand taskTemplate
in the console, you will see that it contains a certain document-fragment
, and already inside it you will find the very template that we need.
What exactly is this document-fragment
, and how can we extract our template from it?
The document-fragment
or just the fragment is the repository of the contents of the template
tag. It is also the reason why the markup from the template
is not displayed on the page. You can see this for yourself if you add styles to the tag itself: for example, the explicitly set width, height, and bright background color. In that case, you will see the template
element on the page, but you won’t see its contents.
If we search for elements inside the template
using querySelector
and other search methods, then we won’t find the elements that we need. They are contained in the content
property of this tag. This property contains document-fragment
, which can be searched using the normal search methods.
<body>
…
<template id="text-template">
<p class="text"></p>
</template>
</body>
If we want to find an element in the template, we need to perform the following search:
var template = document.querySelector('#text-template');
// A template was found in the document.
var content = template.content;
// We obtained the contents, a text fragment.
var text = content.querySelector('.text');
// We found the desired template.
We can shorten this code. For example, we can write the the content as one variable and the sought template as another variable.
var textTemplate = document.querySelector('#text-template').content;
var text = textTemplate.querySelector('.text');
This type of code is more convenient, because the template
element is not typically used by itself in the code. All of the work is done with its content and the template that is stored in this content.
You can change the text and classes in the template, and then you can add elements to the page. This is what we will do in the following steps. In the meantime, find the content
and then the element with the item
class inside it. This is the new task template.
- 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.
- In the value for the
taskTemplate
variable changedocument.querySelector('#task-template')
todocument.querySelector('#task-template').content
. - After it is output to the
taskTemplate
console, declare a variablenewItemTemplate
, which contains an element with thetodo-list-item
class. Look insidetaskTemplate
. - On the next line, output
newItemTemplate
to the console.
Comments