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

kiumad

Mohammad Mirfatemi

Posted on July 3, 2022

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 :)

💖 💪 🙅 🚩
kiumad
Mohammad Mirfatemi

Posted on July 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related