如果已经有 Node.appendChild(),ParentNode.append() 有什么用?

What's the use of ParentNode.append() if there already is Node.appendChild()?

ParentNode.append(): MDN, W3C Spec

Node.appendChild(): MDN, W3C Spec

这两种方法似乎做同样的事情。两者兼而有之有什么用?

您的问题已在您发布的 MDN Link 中得到解答。

Differences to Node.appendChild():

  • ParentNode.append() allows you to also append DOMString object, whereas Node.appendChild() only accepts Node objects.
  • ParentNode.append() has no return value, whereas Node.appendChild() returns the appended Node object.
  • ParentNode.append() can append several nodes and strings, whereas Node.appendChild() can only append one node.

上面引用的文章中MDN差异集的一些结论是:

  • 您不需要使用 document.createTextNode("some text") 创建节点,然后将其附加到元素。您一步完成这些事情,只需在其后附加 append("some text")。
  • 您也可以一步添加多个元素。在动态创建生成内容时创建同时生成的元素组时非常有用。

注意:考虑到 IE 不支持 append()