<body>
<div>
<p id="test"></p>
</div>
<script>
// I'm trying to clone an element
var h1 = document.createElement('h1'); // I create <h1>
h1.innerHTML('test'); // I put some text between this element <h1>test</h1>
document.getElementById('test').appendChild(h1); // I add this h1 to <p id="test"><h1>test</h>
var h1Clone = h1.cloneNode(true); // I use cloneNode to clone h1
// Here I'll clone the <p> tag and add h1Clone to it
var paragraph = document.getElementById('test'); // Look for id="test"
paragraph.appendChild(h1); // Add h1 as <p>'s child
var paragraphClone = paragraph.cloneNode(true); // Clone <p>
paragraphClone.appendChild(h1Clone); // Add h1Clone as <p>'s (clone) child.
paragraph.parentNode.appendChild(paragraphClone); // Finally I add <p>'s clone to <body> tag
</script>
</body>
</html>
您好,我评论了所有内容,以便您了解我正在尝试做的事情。为什么我不能让它工作?
这是我想要的最终 html 结果:
<p id="test"><h1>test</h1></p>
<p id="test"><h1>test</h1></p> <-- clone ->