125

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
  • 11,448
  • 20
  • 86
  • 135
Jarco
  • 1,635
  • 4
  • 14
  • 22

3 Answers3

177

You can use .insertBefore():

parentElement.insertBefore(newElement, parentElement.childNodes[2]);
Obed Parlapiano
  • 3,226
  • 3
  • 21
  • 39
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 14
    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