Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't the same node be inserted at two different places in a document?

I am trying to insert a button node in a document but for some reasons, it's not getting inserted at both places.

the code is below:

var elements = document.querySelectorAll('.Tabelle-Titel-nur-oben');
var buttonElement = document.createElement("Button");
var t0 = document.createTextNode("CLICK ME");
buttonElement.appendChild(t0);
for(var i = 0; i< elements.length; i++)
{

      document.body.insertBefore(buttonElement, elements[i]);
}

In my code, there are two elements which get matched for querySelectorAll. But my button is only get inserted at the second element. If I use two different button instances it works. I would like to know why a button instance does not get inserted in two places?

like image 654
forethought Avatar asked Dec 14 '22 03:12

forethought


1 Answers

Since your buttonElement is a reference to the same object, you need to clone it before adding it:

var elements = document.querySelectorAll('.Tabelle-Titel-nur-oben');
var buttonElement = document.createElement("Button");
var t0 = document.createTextNode("CLICK ME");
buttonElement.appendChild(t0);
for(var i = 0; i< elements.length; i++)
{
    var btnClone = buttonElement.clone(true);
    document.body.insertBefore(btnClone, elements[i]);
}

Or create the button within the loop as @Roberrrt just pointed out as I was about to hit submit.

like image 104
Brian Avatar answered Dec 16 '22 16:12

Brian