Table of Contents Hide
  1. Syntax
  2. Arguments
  3. Returned value
  4. Example

The appendChild() method adds a node as the last child node in the specified parent element.

If the node that is appended as the last child node of the current element already exists in the HTML document and is located in another parent element, it is removed from its current parent element and appended as the last child node in the new parent element. Simply put, a node can be moved from its current position to another location.

If the node to be added is in the same parent to which it is being added, it will simply be moved from its current position to the end of the parent.

Note: If you need to create a new element to append, you must first use the createElement() method and then use the appendChild() method for the element you just created. To insert the element before the specified child node of the current parent, use the insertBefore() method.

Syntax

elem.appendChild(node);

elem is the parent element to which the node passed as an argument will be added.

Arguments

node: the element that will be added to the end of the list of children of the specified parent.

Returned value

Returns a reference to the added node (element).

Example

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Page name</title>
</head>
<body>
 
  <ul id="list1"><li>Coffee</li><li>Tea</li></ul>
  <ul id="list2"><li>Water</li><li id="item2">Milk</li></ul>
 
  <p>Press the button to move the last item in the list</p>
  <button onclick="foo()">Move</button>
 
  <p>Click the button to add a new item to the list</p>
  <button onclick="bar()">Add</button>
 
  <script>
    var i = 1;
 
    function foo() {
      var elem = document.getElementById("list2").lastChild;
      document.getElementById("list1").appendChild(elem);
    }
 
    function bar() {
      var elem = document.createElement("li");
      elem.innerHTML = "Water" + i;
      document.getElementById("list2").appendChild(elem);
      i++;
    }
  </script>
 
</body>
</html>
0 Shares:
Leave a Reply

Your email address will not be published.

You May Also Like