I have an array of elements and I want use inserBefore on each of them as I iterate through the array. It’s supposed to add the element-to-be-inserted after each of the elements in the array but it only adds it to the last element in the array. I thought it was a closure issue but even after using closures i still get the problem. Without closures I tested it by changing the class name to the key value that the array was on and it changed it no problem.
for(var i in elems){
var refElem = elems[i];
refElem.parentNode.insertBefore(elementToInsert, refElem.nextSibling);
}
Here’s the code minus the closures. How do I get the elementToInsert added to each element in the array?
That’s where the trouble arises, you cannot insert one element multiple times into the DOM. If you try to, it will just remove the element from the DOM before inserting it somewhere (again). So you will need to create distinct elements for each turn of the loop, for example by cloning your
elementToInsert.Btw, never use for…in-loops with arrays!