Table of contents
- 1. Summary
- 2. Syntax
- 3. Description
- 4. Example
- 5. Notes
- 6. Specification
Summary
Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.
Syntax
var child = element.appendChild(child);
element
is the parent element.child
is the node to append underneathelement
. Also returned.
Description
The appendChild
method returns a reference to added node.
Example
// Create a new paragraph element, and append it to the end of the document body var p = document.createElement("p"); document.body.appendChild(p);
Notes
If child
is a reference to an existing node in the document, appendChild
moves it from its current position to the new position (i.e. there is no requirement to remove the node from its parent node before appending it to some other node).
This also means that a node can't be in two points of the document simultaneously. So if the node already has a parent, it is first removed, then appended at the new position.
You can use cloneNode 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.)
This method is not allowed to move nodes between different documents. If you want to append node from a different document (for example to display results from AJAX request) you must first use importNode.
Related methods: insertBefore, replaceChild and removeChild.
appendChild()
is one of the fundamental methods of web programming using the DOM. The appendChild()
method inserts a new node into the DOM structure of a document, and is the second part of the one-two, create-and-append process so central to building web pages programmatically.