admin管理员组文章数量:1414605
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?
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?
Share Improve this question edited Dec 1, 2018 at 11:39 AlterSchwede asked Dec 1, 2018 at 11:34 AlterSchwedeAlterSchwede 5831 gold badge5 silver badges11 bronze badges2 Answers
Reset to default 2This 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/
https://jsfiddle/ar5dbn30/16/
var clone = document.getElementById('test').cloneNode(true);
clone.querySelector('.child').innerHTML = "TEST 2"
clone.setAttribute('id', 123)
document.body.appendChild(clone)
Changing cloned element child innerHTML and appending to body. The same can be done with any attributes you want for cloned elements or its childs.
本文标签: javascriptUse js cloneNode to copy ltdivgt template and modify childrenStack Overflow
版权声明:本文标题:javascript - Use js cloneNode to copy <div> template and modify children - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745193020a2647003.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论