mgrubinger / blog

https://www.grooovinger.com/
MIT License
0 stars 0 forks source link

<template> element #27

Open mgrubinger opened 1 year ago

mgrubinger commented 1 year ago

date: '2022-10-25' short: ... for dynamic content

The <template> element is useful if you want to dynamically create markup based on a predefined “template” (great naming right there).

Example markup:

<template>
    <div>
        <h3>any markup, really</h3>
        <!-- watch out for FOUT if you also load relevant styles -->
        <link rel="stylesheet" href="url-to-stylesheet.css">
    </div>
</template>

<div class="my-target"></div>

Example script

// grab the template
const template = document.getElementById('my-template');
// clone the templates content
const clonedTemplate = template.content.firstElementChild.cloneNode(true);
// optionally modify the cloned tree here
// append to `.my-target`
document.targetSelector('.my-target').appendChild(clonedTemplate);

👉 The first child of