can you "AppendChild" same element multiple times in js ? Probably not
Mohammad Mirfatemi
Posted on July 3, 2022
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 :)
💖 💪 🙅 🚩
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
javascript How I Created Vanilla Calendar Pro — A Lightweight and Flexible JavaScript Calendar with TypeScript
November 28, 2024