Ad

JavaScript’s Element.appendChild() Method Behaving Weird

- 1 answer

What i am trying to do is.. appending a common node/element in 3 elements..

const elements = document.getElementsByClassName(“test”);
const newElement = document.createElement(“BUTTON”);
newElement.classList.add(“dummy”);

Array.from(elements).forEach(item => {
item.appendChild(newElement);
});

Expected behaviour is that all .test elements should contain .dummy button..

but actually only last .test element getting that .dummy button..

But if i place that button in loop like this :

const elements = document.getElementsByClassName(“test”);

Array.from(elements).forEach(item => {
const newElement = document.createElement(“BUTTON”);
newElement.classList.add(“dummy”);
item.appendChild(newElement);
});

then all .test elements get that .dummy button..!!

Can anyone explain any particular reason about this JS behaviour ? I have tried to google it but didn’t find any good explanation about this.

Ad

Answer

Thanks @VLAZ Posting it as an answer :

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position" from MDN. It even repeats the same thing in the very next paragraph: "This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position

Ad
source: stackoverflow.com
Ad