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 avaliable!
ParentNode.append() method supports multiple arguments and appending strings.

句法

element.appendChild(aChild)
					

参数

aChild

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

返回值

The returned value is the appended child ( aChild ), except when aChild DocumentFragment , in which case the empty DocumentFragment 被返回。

注意事项

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

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

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

范例

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

规范

规范 状态 注释
DOM
The definition of 'Node.appendChild()' in that specification.
实时标准 无变化自 DOM (文档对象模型) 3 级核心规范 .
DOM (文档对象模型) 3 级核心规范
The definition of 'Node.appendChild()' in that specification.
过时 无变化自 DOM (文档对象模型) 级别 2 核心规范 .
DOM (文档对象模型) 级别 2 核心规范
The definition of 'Node.appendChild()' in that specification.
过时 无变化自 DOM (文档对象模型) 1 级规范 .
DOM (文档对象模型) 1 级规范
The definition of 'Node.appendChild()' in that specification.
过时 初始定义。

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
appendChild Chrome 1 Edge 12 Firefox 1 IE 5 Opera 7 Safari 1.1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改: