How to append a childnode to a specific position

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


You can use .insertBefore():

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

For this you have 3 options .insertBefore(), .insertAdjacentElement() or .insertAdjacentHtml()


.insertBefore()

var insertedElement = parentElement.insertBefore(newElement, referenceElement);

in your case you could do as on Felix Kling answer

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

.insertAdjacentElement()

referenceElement.insertAdjacentElement (where, newElement);

in your case it would be

parentElement.children[1].insertAdjacentElement("afterEnd", newElement);

.insertAdjacentHTML()

referenceElement.insertAdjacentElement (where, newElementHTML);

in your case it would be

parentElement.children[1].insertAdjacentElement("afterEnd", "<td>newElementHTML</td>");

To insert a child node at a specific index

Simplified,

Element.prototype.insertChildAtIndex = function(child, index) {
  if (!index) index = 0
  if (index >= this.children.length) {
    this.appendChild(child)
  } else {
    this.insertBefore(child, this.children[index])
  }
}

Then,

var child = document.createElement('div')
var parent = document.body
parent.insertChildAtIndex(child, 2)

Tada!

Be aware of when extending natives could be troublesome