Node.appendChild()

The appendChild() method of the Node interface 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. Copies made with cloneNode are not 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.

Note: Unlike this method, the Element.append() method supports multiple arguments and appending strings. You can prefer using it if your node is an element.

Chaining does not work, due to appendChild() returning the child element:

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

Sets aBlock to <b></b> only, meaning you cannot chain further actions on block, like performing several chained appendChild.

Syntax

appendChild(aChild);

Parameters

aChild

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

Return value

A Node that is the appended child (aChild), except when aChild is a DocumentFragment, in which case the empty DocumentFragment is returned.

Exceptions

HierarchyRequestError DOMException

Thrown when the constraints of the DOM tree are violated, that is if one of the following cases occurs:

NotFoundError DOMException

Thrown if the parent of aChild is not the current node.

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

Specification
DOM Standard (DOM)
# dom-node-appendchild

Browser compatibility

BCD tables only load in the browser

See also