I have been reading the documentation on the <template> tag, and I can't seem to understand how it is different from simply using a <div> that is display: none;
Documentation: template tag
<template> example
<template id="productrow">
<tr>
<td class="record"></td>
<td></td>
</tr>
</template>
VS
<div> example
<div id="productrow" style="display: none">
<tr>
<td class="record"></td>
<td></td>
</tr>
</div>
- On a low level, how does the browser handle these 2 examples differently?
- Are certain JS methods or HTML attributes different or not available?
PS: I am aware of browser compatibility differences
Consider:
And:
Are these going to behave the same when the browser renders them? (Spoiler: no.)
To address your specific questions, though:
For one, the HTML inside a
<template>does not become DOM elements that are children of the<template>. It becomes children of an "inert" DocumentFragment (indirectly; this is a simplification) where they exist as nodes but do not "do" anything, as in the example above.In addition to being "inert," the template contents have no "conformance requirements." Your
<tr>example above is a good one. See what happens here:In a normal document, a
<tr>can't be a child of a<div>, so the browser just removes it. In a<template>, that requirement doesn't exist. You would find the same with, say,<div style="{{myStyle}}">. In a document, the browser would throw away thestyleattribute because its value is invalid; in a<template>it would not. This is what makes<template>useful for, well, templating.If you want to know more about how
<template>s are rendered, I suggest reading the section about it in the HTML spec. It's not easy reading, and parts may be incomprehensible, but you stand to learn a lot.The
<template>element has thecontentattribute, which points to the DocumentFragment discussed above.