The appendChild()
method of the Node
interface adds a node to the end of the list of children of a specified parent node.
Note: 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.
If the given child is a DocumentFragment
, the entire contents of the DocumentFragment
are moved into the child list of the specified parent node.
appendChild()
returns the newly appended node, or if the child is a DocumentFragment
, the emptied fragment.
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.
A Node
that is the appended child (aChild
), except when aChild
is a DocumentFragment
, in which case the empty DocumentFragment
is returned.
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. 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.
appendChild()
returns the newly appended node, instead of the parent node. This means you can append the new node as soon as it's created without losing reference to it:
const paragraph = document.body.appendChild(document.createElement("p"));
On the other hand, you cannot use appendChild()
in a fluent API fashion (like JQuery).
document.body
.appendChild(document.createElement("p"))
.appendChild(document.createElement("p"))
.appendChild(document.createElement("p"));
const p = document.createElement("p");
document.body.appendChild(p);
In this example, we attempt to create a nested DOM structure using as few temporary variables as possible.
const fragment = document.createDocumentFragment();
const li = fragment
.appendChild(document.createElement("section"))
.appendChild(document.createElement("ul"))
.appendChild(document.createElement("li"));
li.textContent = "hello world";
document.body.appendChild(fragment);
It generates the following DOM tree:
<section>
<ul>
<li>hello world</li>
</ul>
</section>