duplicate elements using element.cloneNode()
Elaborating on an earlier answer, the created element can be cloned to make a copy using:
element.cloneNode(true)
See: https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
The true parameter value tells the .cloneNode method to deep clone, meaning it should include the subtree (specifying descendent elements and text nodes).
The following snippet clones the div in the question with and without the deep clone parameter set. When the deep clone parameter is not set, the element is empty.
One caveat to be aware of is that if the original element has an id attribute set, it should be re-set to hold a different value for all subsequent clones to avoid having elements with duplicate ids in the page.
var a = "asd";
const added = document.createElement("div");
const addedP = document.createElement("p")
addedP.innerText = a;
added.append(addedP);
// make a copy of added, including subtree;
copyAdded = added.cloneNode(true)
// clone again without the parameter set true;
anotherCopy = added.cloneNode()
document.body.append(added);
document.body.append(copyAdded);
document.body.append(anotherCopy);
div {
min-height: 20px;
border: 1px solid black;
background: yellow;
margin: 5px;
}
The first div was created in javascript. The second and third <i>cloned</i> from the first. Note the last paragraph lacks content because the <i>deep clone</i> parameter of <b>element.cloneNode()</b> was not set. The second paragraph used <b>element.cloneNode(true)</b> to specify a deep clone where the element and its subtree is duplicated.
forstatement.