How to append a childnode to a specific position

JavascriptDomParent Child

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

You can use .insertBefore():

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

Solution 2 - Javascript

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>");

Solution 3 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJarcoView Question on Stackoverflow
Solution 1 - JavascriptFelix KlingView Answer on Stackoverflow
Solution 2 - JavascriptMauricioJuanesView Answer on Stackoverflow
Solution 3 - JavascriptLeonard PauliView Answer on Stackoverflow