javascripthtmlhtml-templates

How to use <template> with dynamic IDs?


Given a HTML-template like this:

<template id="paragraph-template">
<p>Hi, I am a paragraph</p>
</template>

I load and append this template via JS, like so:

let templateInstance = document.getElementById("paragraph-template");
myContainer.appendChild(templateInstance)

Now I'd like to add the template multiple times (i.e. in a for-loop) and I want the <p>-elements to each have a unique id, so the result would look like e.g.:

<div>
<p id="p1">Hi, I am a paragraph</p>
<p id="p2">Hi, I am a paragraph</p>
<p id="p3">Hi, I am a paragraph</p>
<div>

How can I achieve this with HTML-templates?

EDIT: The example I provide here is minified – In the real world I have a template with many elements, which should all get a unique ID.


Solution

  • I suggest you :

        let templateInstance = document.getElementById("paragraph-template");
        for(var i=1;i<4;i++){
            let clone = document.importNode(templateInstance .content, true);       
            clone.querySelector('p').id = "p"+i;
            myContainer.appendChild(clone); 
        }