DEV Community

Mohammad Mirfatemi
Mohammad Mirfatemi

Posted on

can you "AppendChild" same element multiple times in js ? Probably not

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 ?
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

and use it :

const d1 = document.createElement("div");
const d2 = document.createElement("div");
appendChildMultiple(d1);
appendChildMultiple(d2);
Enter fullscreen mode Exit fullscreen mode

an example on Codepen :

Do you think this method has good performance? Leave a comment below :)

Top comments (1)

Collapse
 
fridaycandours profile image
Friday candour

I solve this problem by getting the raw html and insert into Dom (leaving the Dom to accept as a brand new one even if their multiple of it).

This leaves the browser

  • create a div

  • append the element(s) to the div

  • now get it's inner html, that's what you can use multiple times

  • you can insert it as multiple times as you want as a form of reusable item and you can change it's data easily during the process.

Probably not a good practice but it's easier to handle a multiple number of html all together like a reusable item.