JavaScript’s Node.appendChild()
method adds a child node to the end of the list of the Node
’s children. If the child node is a reference to an existing node in the document, the method moves the node from its current position to the new position.
Syntax
Node.appendChild(parameter)
Parameters
A Node
object to append to the parent node.
Return value
The appendChild()
method returns the appended node, except when the node is a DocumentFragment
, in which case the method returns the empty DocumentFragment
.
Exceptions
HierarchyRequestError
DOMException
Thrown when the constraints of the DOM are violated (for example, when the appended node is an ancestor of the parent node, which leads to a cycle).
Examples
Here are some examples of using the JavaScript appendChild()
method.
Appending an element
Suppose we have the following unordered list to which we would like to add li
elements:
What should we do?
Well, we should create li
elements and append them to the ul
element:
let list = document.getElementById('list');
let languages = ['C#', 'JavaScript', 'Python'];
languages.forEach(language => {
let li = document.createElement('li');
li.textContent = language;
list.appendChild(li);
});
Now our HTML looks like this:
<ul id="list">
<li>C#</li>
<li>JavaScript</li>
<li>Python</li>
</ul>
Here is how our HTML looks like in the browser:
- C#
- JavaScript
- Python
But what did we do?
First we used the getElementById()
method to select the ul
element by its id
. Then we declared an array of programming languages. For each language, we created a new li
element, set the element’s textContent
, and appended the li
element to the ul
element.
Moving a node
What if we wanted to move programming languages from one list to another? We can do that by using the appendChild()
method.
First, let’s create another unordered list so that our lists look like this:
<ul id="list">
<li>C#</li>
<li>JavaScript</li>
<li>Python</li>
</ul>
<ul id="newList">
</ul>
Then we can proceed to moving one language from the first list to the second:
let newList = document.getElementById('newList');
let language = document.querySelector('#list li:first-child');
newList.appendChild(language);
Here is our HTML after the move:
<ul id="list">
<li>JavaScript</li>
<li>Python</li>
</ul>
<ul id="newList">
<li>C#</li>
</ul>
What is the difference between appendChild() and append()?
The appendChild()
and append()
methods have some noteworthy differences:
- With
Node.appendChild()
, you can append oneNode
object at a time; withElement.append()
, you can append severalNode
and string objects. appendChild()
returns the appendedNode
object;append()
does not have a return value.
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
appendChild() |
1 | 12 | 1 | 5 | 7 | 1.1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 |