appendChild (W3C DOM Core method)

Spec
Version Depr. Static
DOM1 No No
Browser support (more…)
IE5.5+ FF3+ SA1.3+ OP9+
Full Full Buggy Buggy
Returns
Node
Throws
HIERARCHY_REQUEST_ERR, WRONG_DOCUMENT_ERR, NO_MODIFICATION_ALLOWED_ERR

Example

node.appendChild(newnode);

The example above will append newnode at the end of node's list of children.

So if node is actually an HTML p element, like this:

<p>Love always</p>

And newnode is a Text node with the value wins, then the operation above would result in this:

<p>Love always wins</p>

Arguments

new node (Node) required

The new node to be added to this node. If the new node has any children these are also added recursively, preserving the new node's sub-tree.

Description

Add a new node (and its subtree, if applicable) to the end of the list of children of this node.

If the new child is already present in the DOM tree it is first removed (effectively moving it). If the new child is a DocumentFragment node then the entire contents of the document fragment are appended, but the fragment node itself is not (therefore using a document fragment is a good way of building and attaching several nodes at once).

Return value

The node that was added

Compatibility

Internet Explorer Firefox Safari Opera
5.5 6.0 7.0 1.5 2.0 3.0 1.3 2.0 3.0 9.0 9.5
Full Full Full Buggy Buggy Full Buggy Buggy Buggy Buggy Buggy

The specification says that this method should throw a DOMException when attempting to append a node which was created in a different document (code 4: WRONG_DOCUMENT_ERR). Therefore if a browser supports this and does not throw an exception, this is considered a bug, and is what happens in Opera, Firefox 1.5 and 2 and Safari 3.

DANGER: Potential crash bug in Safari 1.3 and 2

In Safari 1.3 and 2 attempting to append a node which was created in a different document causes the browser to crash.

Tip: So don’t use this method to move nodes between documents

Overall then — don't use appendChild to move nodes between documents, use importNode instead, because that's what it's for.

User-contributed notes

Related Products