The Node.appendChild()
method 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()
can be used 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.
If the given child is a DocumentFragment
, the entire contents of the DocumentFragment
are moved into the child list of the specified parent node.
element.appendChild(aChild);
The returned value is the appended child except when the given child is a DocumentFragment
, in which case the empty DocumentFragment
is returned.
Chaining may not work as expected due to appendChild()
returning the child element:
var aBlock = doc.createElement('block').appendChild(doc.createElement('b'));
Sets aBlock
to <b></b>
only, which is probably not what you want.
// Create a new paragraph element, and append it to the end of the document body var p = document.createElement("p"); document.body.appendChild(p);
Specification | Status | Comment |
---|---|---|
DOM The definition of 'Node.appendChild()' in that specification. | Living Standard | No change from Document Object Model (DOM) Level 3 Core Specification. |
Document Object Model (DOM) Level 3 Core Specification The definition of 'Node.appendChild()' in that specification. | Obsolete | No change from Document Object Model (DOM) Level 2 Core Specification. |
Document Object Model (DOM) Level 2 Core Specification The definition of 'Node.appendChild()' in that specification. | Obsolete | No change from Document Object Model (DOM) Level 1 Specification. |
Document Object Model (DOM) Level 1 Specification The definition of 'Node.appendChild()' in that specification. | Obsolete | Initial definition. |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | Yes | Yes | Yes | 9 | Yes | Yes |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | Yes | Yes | Yes | Yes | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild