Template tag in HTML and its uses

Hello, didn't know that template was an html tag until now. Just read a bit about it. From what I've understood, we can think of it like a normal div element, it will be in the DOM ect except that its content won't be visible to the users. In order to make it visible, we must use javascript and "clone" it I think and this way it will be visible? Can someone confirm if the above statement is correct pls, feel free to add up to it if needed. Also, what about its use case? Why not just use a div with display being changed each time we need to make something visible or not pls
13 Replies
Faker
FakerOP2mo ago
It seems that the DOM doesn't render whatever is inside the template tag though
Faker
FakerOP2mo ago
No description
Jochem
Jochem2mo ago
you use it as a template you write a component in there that you need to reuse, then clone it as many times as you need to make copies
Faker
FakerOP2mo ago
ahh ok I see it's really just a component like we have in JS frameworks?
Jochem
Jochem2mo ago
that's the main use case, but in vanilla JS and HTML
Faker
FakerOP2mo ago
yepp I see Thanks !
ἔρως
ἔρως2mo ago
important: you clone the .contents property, NOT the tag itself the .contents is the property that refers to that document fragment also, you have to do a deep clone so, in js, you do something like this:
let frag = template.contents.cloneNode(true);
let frag = template.contents.cloneNode(true);
and since it is a document fragment, you can use all the normal methods, like .querySelectorAll you also can just add the fragment directly to the document
Faker
FakerOP2mo ago
yep noted, ty !
13eck
13eck2mo ago
it will be in the DOM ect except that its content won't be visible to the users.
Also, it's "etc", not "ect".
Faker
FakerOP2mo ago
sorry, I often miss spell this
13eck
13eck2mo ago
Sadly it’s a very common mistake
Faker
FakerOP2mo ago
will try to prevent that in the future (be I'm sure will do the same mistake one or two times 😂 )
ἔρως
ἔρως2mo ago
dont worry, i started calling "brian" to my brain because i misspell it often (eh, grammar isnt strong with me today too)

Did you find this page helpful?