Introduction to the JavaScript appendChild() method
The appendChild() is a method of the Node interface. The appendChild() method allows you to add a node to the end of the list of child nodes of a specified parent node.
The following illustrates the syntax of the appendChild() method:
In this method, the childNode is the node to append to the given parent node. The appendChild() returns the appended child.
If the childNode is a reference to an existing node in the document, the appendChild() method moves the childNode from its current position to the new position.
JavaScript appendChild() examples
Let’s take some examples of using the appendChild() method.
1) Simple appendChild() example
Suppose that you have the following HTML markup:
<ulid="menu"></ul>Code language: HTML, XML (xml)
The following example uses the appendChild() method to add three list items to the <ul> element:
functioncreateMenuItem(name){letli=document.createElement('li');li.textContent=name;returnli;}// get the ul#menuconstmenu=document.querySelector('#menu');// add menu itemmenu.appendChild(createMenuItem('Home'));menu.appendChild(createMenuItem('Services'));menu.appendChild(createMenuItem('About Us'));Codelanguage:JavaScript (javascript)
How it works:
First, the createMenuItem() function create a new list item element with a specified name by using the createElement() method.
Second, select the <ul> element with id menu using the querySelector() method.
Third, call the createMenuItem() function to create a new menu item and use the appendChild() method to append the menu item to the <ul> element
Output:
Put it all together:
2) Moving a node within the document example
Assuming that you have two lists of items:
The following example uses the appendChild() to move the first child element from the first list to the second list:
How it works:
First, select the first element by its id (first-list) using the querySelector() method.
Second, select the first child element from the first list.
Third, select the second element by its id (second-list) using the querySelector() method.
Finally, append the first child element from the first list to the second list using the appendChild() method.
Here are the list before and after moving:
Summary
Use appendChild() method to add a node to the end of the list of child nodes of a specified parent node.
The appendChild() can be used to move an existing child node to the new position within the document.
// get the first list
const firstList = document.querySelector('#first-list');
// take the first child element
const everest = firstList.firstElementChild;
// get the second list
const secondList = document.querySelector('#second-list');
// append the everest to the second list
secondList.appendChild(everest)
Code language: JavaScript (javascript)