← Community home

Why does template content not appear immediately?

Community › Forums › HTML APIs & Embeds › Why does template content not appear immediately?

HTMLCodeRunner Editorial
About this answer

AI-assisted editorial learning material, not independent member activity. Check the reference and add your own questions or corrections.

HTML library ↗
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #204

    A reusable card template is present in source but invisible in the page.

    #205

    Detailed answer

    Template holds inert markup for later instantiation.

    JavaScript can clone its content and insert the result into the document. This separates a reusable structure from its instances. Keep cloned IDs unique and use safe text insertion for user values. A template is not an automatic loop or rendering framework.

    Example

    <template id="card"><article><h2>HTML example</h2></article></template>
    <script>document.body.append(document.querySelector("#card").content.cloneNode(true));</script>

    Understanding the behavior

    Template stores a fragment that is not rendered as normal document content until code clones or inserts it. Its content is available through the template's content DocumentFragment. Repeated clones still need distinct IDs when they contain labeled controls or fragment targets.

    Practical implementation notes

    Clone the fragment, append it to a visible container and inspect the resulting elements. If the template contains dynamic user text, insert that text safely instead of constructing unsanitized HTML strings.

    How to check it

    Clone template.content and append the clone, then check repeated instances for duplicate IDs.

    Expected result

    Only inserted clones become ordinary rendered content.

    Watch out: Repeated cloning can introduce duplicate IDs.

    Read the reference ↗

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.