HTML DOM appendChild() Method

HTMLWeb DevelopmentFront End Technology

The HTML DOM appendChild() method is used to create and add a text node at the end of the list of child nodes. The appendChild() method can also be used to move an element from current position to a new position. Using appendChild() you can add new values to a list and can even add a new paragraph under another paragraph.

Syntax

Following is the syntax for appendChild() Method −

node.appendChild( node )

Here, the parameter node is the object that you want to append. It is a compulsory parameter value.

Example

Let us see an example of appendChild() Method −

 Live Demo

<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a paragraph and append it to the div</p>
<div id="SampleDIV">
A DIV element
</div>
<button onclick="AppendP()">Append</button>
<script>
   var x=1;
   function AppendP() {
      var paragraph = document.createElement("P");
      paragraph.innerHTML = "This is paragraph "+x;
      document.getElementById("SampleDIV").appendChild(paragraph);
      x++;
   }
</script>
</body>
</html>

Output

This will produce the following output −

After clicking append 3 times: −

In the above example −

We have created a div with id “SampleDIV”. The appended node will act as child of this div.

<div id="SampleDIV">
A DIV element
</div>

We have then a button named “Append” which will execute the function AppendP()

<button onclick="AppendP()">Append</button>

The AppendP() function first creates a paragraph (p) element and assigns it to variable paragraph. Then some text is added to paragraph using innerHTML and a variable x is appended to text. This variable is incremented each time we click the ”Append” button. At last we append the newly created paragraph as a child node of the div element −

var x=1;
function AppendP() {
   var paragraph = document.createElement("P");
   paragraph.innerHTML = "This is paragraph "+x;
   document.getElementById("SampleDIV").appendChild(paragraph);
   x++;
}
raja
Updated on 20-Feb-2021 06:28:21

Advertisements