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.
var child = element.appendChild(child);
elementis the parent element.
childis the node to append underneath
element. Also returned.
appendChild method returns a reference to added node.
// Create a new paragraph element, and append it to the end of the document body var p = document.createElement("p"); document.body.appendChild(p);
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
Node.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
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.