Javascript 如何将子节点附加到特定位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5882768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:21:12  来源:igfitidea点击:

How to append a childnode to a specific position

javascriptdomparent-child

提问by Jarco

How can I append a childNode to a specific position in javascript?

如何将 childNode 附加到 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.)

我想将 childNode 添加到 div 中的第三个位置。它后面还有其他节点需要向后移动(3 变为 4 等)

回答by Felix Kling

You can use .insertBefore():

您可以使用.insertBefore()

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

回答by MauricioJuanes

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

为此,您有 3 个选项 .insertBefore()、.insertAdjacentElement() 或 .insertAdjacentHtml()



.insertBefore()

.insertBefore()

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

in your case you could do as on Felix Kling answer

在您的情况下,您可以按照Felix Kling 的回答进行操作

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


.insertAdjacentElement()

.insertAdjacentElement()

referenceElement.insertAdjacentElement (where, newElement);

in your case it would be

在你的情况下,它会是

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


.insertAdjacentHTML()

.insertAdjacentHTML()

referenceElement.insertAdjacentElement (where, newElementHTML);

in your case it would be

在你的情况下,它会是

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

回答by 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

请注意何时扩展本地人可能会很麻烦