Node.appendChild() - Web APIs 编辑

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position. The Node.cloneNode() method can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode will not be automatically kept in sync.

If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node.

Newer API available!
The ParentNode.append() method supports multiple arguments and appending strings.

Syntax

element.appendChild(aChild)

Parameters

aChild
The node to append to the given parent node (commonly an element).

Return value

The returned value is the appended child (aChild), except when aChild is a DocumentFragment, in which case the empty DocumentFragment is returned.

Notes

Chaining may not work as expected, due to appendChild() returning the child element:

let aBlock = document.createElement('block').appendChild( document.createElement('b') );

Sets aBlock to <b></b> only, which is probably not what you want.

Example

// Create a new paragraph element, and append it to the end of the document body
let p = document.createElement("p");
document.body.appendChild(p);

Specifications

SpecificationStatusComment
DOM
The definition of 'Node.appendChild()' in that specification.
Living StandardNo change from Document Object Model (DOM) Level 3 Core Specification.
Document Object Model (DOM) Level 3 Core Specification
The definition of 'Node.appendChild()' in that specification.
ObsoleteNo change from Document Object Model (DOM) Level 2 Core Specification.
Document Object Model (DOM) Level 2 Core Specification
The definition of 'Node.appendChild()' in that specification.
ObsoleteNo change from Document Object Model (DOM) Level 1 Specification.
Document Object Model (DOM) Level 1 Specification
The definition of 'Node.appendChild()' in that specification.
ObsoleteInitial definition.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:94 次

字数:6200

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文