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.