appendChild()
Introduction to the JavaScript appendChild()
method
appendChild()
methodThe 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
appendChild()
examplesLet’s take some examples of using the appendChild()
method.
1) Simple appendChild()
example
appendChild()
exampleSuppose that you have the following HTML markup:
The following example uses the appendChild()
method to add three list items to the <ul>
element:
How it works:
First, the
createMenuItem()
function create a new list item element with a specified name by using thecreateElement()
method.Second, select the
<ul>
element with idmenu
using thequerySelector()
method.Third, call the
createMenuItem()
function to create a new menu item and use theappendChild()
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 thequerySelector()
method.Second, select the first child element from the first list.
Third, select the second element by its id (
second-list
) using thequerySelector()
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.
Last updated