1

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?

asked Feb 6, 2013 at 22:26

3 Answers 3

4

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!

answered Feb 6, 2013 at 23:07
Sign up to request clarification or add additional context in comments.

1 Comment

I find that adding .cloneNode(true) to the end of the element being inserted solves this.
2

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.

https://developer.mozilla.org/en-US/docs/DOM/Node.cloneNode

answered Feb 6, 2013 at 23:22

Comments

1

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.

answered Mar 17, 2016 at 10:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.