Javatpoint Logo
Javatpoint Logo

JavaScript appendchild() method

The appendChild() is a method of the Node interface in JavaScript. The appendChild() method enables us to add a node to the end of a specified parent node's child node list.

Syntax:

The syntax of the appendchild() method is:

In the syntax, the childNode is the node that adds to the specified parent node. The appendChild() method returns the appended child node. The appendChild() method transfers the childNode from its current position to the new position if the childNode is relative to an existing node in the document.

JavaScript appendChild() method examples

Now, we will take few examples of appendChild(), which helps to understand how it works.

Example 1: Simple appendChild() example

If we have an HTML list and want to add a new item to the end, we could use the appendChild() method.

Output: After executing this above code, we will get the output as shown below:

JavaScript appendchild() method

As we have seen above there is a Append button, when we click on this button, the appendChild() method add the child node value to its parent node, as shown below:

JavaScript appendchild() method

Example 2: Multiple nodes appends dynamically

In this example, we append the multiple nodes dynamically in the parent node.

Output: After executing the above code, we will get the output as shown below:

JavaScript appendchild() method

As we have seen in the screenshot, there is a Submit button. When we click on this button, the appendChild() method add the multiple child nodes dynamically, as shown below:

JavaScript appendchild() method

Explanation:

  • Firstly, we create a new <ul> element using a createElement() function.
  • After that, we create <li> elements dynamically and append them to the <ul>
  • Finally, we append the <ul> element to <div>

Example 3: Moving a node within the document

Now, let's take an example to understand how we can move a node within the document.

Output: After executing the above code, we will get the output as shown below:

JavaScript appendchild() method

Explanation:

  1. First of all, we need to choose the first element from its first list using the querySelector()
  2. Now, choose the first child element from the first list.
  3. After that, choose the second element from its second list using the querySelector()
  4. Finally, append the first child element to the second list using the appendChild()





Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA