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 pls13 Replies
It seems that the DOM doesn't render whatever is inside the
template tag though
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
ahh ok
I see
it's really just a component like we have in JS frameworks?
that's the main use case, but in vanilla JS and HTML
yepp I see
Thanks !
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:
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 documentyep noted, ty !
it will be in the DOM ect except that its content won't be visible to the users.Also, it's "etc", not "ect".
sorry, I often miss spell this
Sadly it’s a very common mistake
will try to prevent that in the future (be I'm sure will do the same mistake one or two times 😂 )
dont worry, i started calling "brian" to my brain because i misspell it often
(eh, grammar isnt strong with me today too)