使用js cloneNode复制<div>模板并修改children

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

我想使用 cloneNode 并避免 JQuery 在 DOM 中复制 html 模板,修改(嵌套的)children 及其 ID(并附加到一个元素)。

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

但是,在将克隆添加到文档之前,getElementById 不适用于克隆。 在更改 children 的 id 之前,我无法将克隆添加到文档中,所以有点 catch 22...

是否有最先进的技术,non-JQuery 在文档中使用 html "template" 的方法?

这对我有用:

<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);

请在此处查看@CodePen: https://codepen.io/animatedcreativity/pen/8ff7cdb8cffc760c17a03215171faf5c/

https://jsfiddle.net/ar5dbn30/16/

var clone = document.getElementById('test').cloneNode(true);
clone.querySelector('.child').innerHTML = "TEST 2"
clone.setAttribute('id', 123)
document.body.appendChild(clone)

更改克隆的元素子 innerHTML 并附加到正文。可以对克隆元素或其子元素所需的任何属性执行相同的操作。