This content originally appeared on DEV Community and was authored by Mohammad Mirfatemi
in this case :
var d1 = document.createElement('div');
var d2 = document.createElement('div');
var p = document.createElement('p');
d1.appendChild(p); // d1 has p now
d2.appendChild(p); // d2 has p now
// but where is p in d1 ?
we cannot append "p" multiple times because in the DOM, being a tree of nodes, one node can have only one parent, it cannot have multiple parents.
But solution !
We can use cloneNode() , but I use another way
I want to use a function
like this :
//main function
function appendChildMultiple(parent) {
//check function argument is an element
if (parent.nodeType !== undefined) {
const pTag = document.createElement("p");
pTag.innerText = "This is the appended element";
//finally append child to parent
parent.appendChild(pTag);
}
}
and use it :
const d1 = document.createElement("div");
const d2 = document.createElement("div");
appendChildMultiple(d1);
appendChildMultiple(d2);
an example on Codepen :
Do you think this method has good performance? Leave a comment below :)
This content originally appeared on DEV Community and was authored by Mohammad Mirfatemi

Mohammad Mirfatemi | Sciencx (2022-07-03T07:47:59+00:00) can you “AppendChild” same element multiple times in js ? Probably not. Retrieved from https://www.scien.cx/2022/07/03/can-you-appendchild-same-element-multiple-times-in-js-probably-not/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.