DEV Community

_Khojiakbar_
_Khojiakbar_

Posted on

Dynamic DOM Element Creation : <template>

In HTML

  1. Create parent div
    <!---------------  Parent div -------------->
    <div id="parent" class="card m-5 mx-auto" >
        <h1>Hello Template</h1>
    </div>
Enter fullscreen mode Exit fullscreen mode
  1. Create template:
<!----------------- Template tag ------------>
    <template id="template">
        <div class="card d-flex">
            <img id="temp-img" src="https://picsum.photos/id/293/100/100" alt="smth">
            <h1>Template title</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi, architecto dolor eius fugiat incidunt ipsa iure iusto officiis recusandae rerum!</p>
        </div>
    </template>
Enter fullscreen mode Exit fullscreen mode

In CSS:

#parent{
    width: 43%;
}
.card {
    width:500px;
    padding: 20px;
}
.card h1{
    font-size: 50px;
}
#temp-img {
    margin: 0 auto;
    width: 400px;
    height: 300px;
}
Enter fullscreen mode Exit fullscreen mode

In Javascript:

  • Call from HTML
const parent = document.querySelector('#parent');
const template = document.querySelector('#template');
Enter fullscreen mode Exit fullscreen mode
  • Clone the template
clonedTemplate = template.content.cloneNode(true);
Enter fullscreen mode Exit fullscreen mode
  • Append the new cloned template to the parent
parent.prepend(clonedTemplate);
Enter fullscreen mode Exit fullscreen mode

Billboard image

Detect & resolve downtimes before users even know

Trusted by Vercel, Render, LinkedIn, and thousands of teams, Checkly monitors your website or application, sends real-time alerts during downtimes, and speeds up recovery with full-stack tracing.

Start Monitoring

Top comments (0)

Image of Bright Data

Feed Your Models Real-Time Data – Enhance your AI with up-to-the-minute data.

Utilize our live data feeds for dynamic model training, ensuring your AI systems are always ahead.

Access Real-Time Data

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay