105

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.)

ObiHill
  • 10,952
  • 18
  • 82
  • 127
Jarco
  • 1,406
  • 3
  • 13
  • 22

3 Answers3

149

You can use .insertBefore():

parentElement.insertBefore(newElement, parentElement.children[2]);
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
  • 13
    Can you explain why you've chosen to go `parentElement.children` rather than `parentElement.childNodes`? The former lists only children which are `Element`s, thus ignoring nodes which are `Text`s, for example... Wouldn't it be better to assume that the child nodes may include all types of nodes??? – mike rodent Oct 12 '17 at 11:26
  • 1
    @mikerodent For example, when you work with list items `
  • ` in an ordered list `
      `, you wouldn't want to have the white space indentation to count as a child (assuming the HTML document is pretty).
  • – Yeti Feb 05 '19 at 12:21
  • 1
    Using childNodes over children is the right way to go here. – brainkim Oct 30 '19 at 18:37