How to append a childnode to a specific position

会有一股神秘感。 提交于 2019-11-28 18:08:14

You can use .insertBefore():

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!