How to append a childnode to a specific position

Jarco picture Jarco · May 4, 2011 · Viewed 69.8k times · Source

How can I append a childNode to a specific position in javascript?

I want to add a childNode to the 3rd position in a div. There are other nodes behind it that need to move backwards (3 becomes 4 etc.)

Answer

Felix Kling picture Felix Kling · May 4, 2011

You can use .insertBefore():

parentElement.insertBefore(newElement, parentElement.children[2]);