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?
3 Answers 3
It's supposed to add the element-to-be-inserted after each of the elements
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!
1 Comment
.cloneNode(true) to the end of the element being inserted solves this.Just like Bergi said, the element you are inserting is actually being added and then removed from the node.
for(var i in elems){
var refElem = elems[i];
refElem.parentNode.insertBefore(elementToInsert.CloneNode(), refElem.nextSibling);
}
You can also inform the parameter 'deep', which will clone all the child nodes too.
Comments
just a little correction of the post before:
for(var i in elems){
var refElem = elems[i];
refElem.parentNode.insertBefore(elementToInsert.cloneNode(), refElem.nextSibling);
}
the function cloneNode() starts with a lowercase.