Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use js cloneNode to copy <div> template and modify children

I want to use cloneNode and avoid JQuery to copy a html template in DOM, modify the (nested) children and their ids (and append to an element).

  var clone = itm.cloneNode(true); 
  clone.id = 'c' + tid; //replace with new, unique id
  itm = clone.getElementById('childtemplateid');
  ...

However, getElementById does not work on clone before it is added to document. I cannot add the clone to the document before I have changed the ids of the children so a little bit of catch 22...

Is there a state of the art, non-JQuery way do use an html "template" in document?

like image 480
AlterSchwede Avatar asked Dec 06 '25 18:12

AlterSchwede


1 Answers

This is working for me:

<div id="test1"><div id="test2"></div></div>

var test3 = document.querySelector("#test1").cloneNode(true);
test3.setAttribute("id", "test3");
test3.querySelector("#test2").setAttribute("id", "test4");
console.log(test3);

Please check @ CodePen here: https://codepen.io/animatedcreativity/pen/8ff7cdb8cffc760c17a03215171faf5c/

like image 123
Rehmat Avatar answered Dec 09 '25 06:12

Rehmat