Search code examples
javascriptclone

How to change inner div's when cloning a template?


I have a template that I'm cloning to make Single Page Application. Inside this template are some div's that should have a unique id's so that it should be working individually when I open multiple apps(clone multiple divs)

<template id="templ">
<div id="name"></div>
<div id="btn"> 
  <fieldset id="fld">
  <input type="text" id="userMessage"placeholder="Type your message…"   autofocus>
  <input type="hidden">
  <button id="send" >Save</button>
  </fieldset>
 </div>
</template>

and I'm cloning it like this

 var i =0
let template = document.querySelector('#templ')
let clone = document.importNode(template.content, true)
clone.id = 'name' + ++i // I can't change the Id o this name div
document.querySelector('body').appendChild(clone)

Thanks


Solution

  • clone.id is undefined since clone is a #document-fragment with two children.

    You need to query the 'name' child and change its id, for example like this:

    const template = document.querySelector('#templ')
    const body = document.querySelector('body')
    
    function appendClone(index){
        let clone = document.importNode(template.content, true)
        clone.getElementById('name').id = 'name' + index
        // all other elements with IDs
        body.appendChild(clone)
    }
    

    Then you can iterate over the amount of clones and simply call the function with the loop index:

    let clones = 5
    for (let i = 0; i < clones; i++){
        appendClone(i)
    }