我想将多个 id 为hello的 div副本附加到 id 为container的 div中。我如何使用 javascript 做到这一点?
<div id="container">
</div>
<div id="hello">
<p>Hello</p>
</div>
使用cloneNode
和appendChild
。
由于id
s 在文档中应该是唯一的,所以我改用类hello
来代替。
function makeCopy() {
const target = document.getElementById("container");
const source = document.querySelector(".hello");
const clone = source.cloneNode(true);
target.appendChild(clone);
}
.hello {
padding: 3px;
margin: 3px;
border: 1px dotted orange;
}
<div id="container">
This is the container.
</div>
<button onclick="makeCopy()">Add a clone of hello above</button>
<div class="hello">
<p>Hello</p>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句