Adding new node to a document

To make the creation method of the document object useful by adding the created node to the document, the DOM node method, such as appendChild() or insertBefore(), is needed to add the new node to the document.

<div id="div1" title="DanD">
This page is about me!

The above code has a div element with a child text node (and attribute nodes). Let’s say that you want to create another div element as the last child node of the div1 element node, then you can use a combination of document.createElement(), document.createTextNode(), and the DOM node method appendChild().

Step 1

var MeDiv = document.getElementById("div1");

This grabs the div1 element by its id.

Step 2

var InnerDiv = document.createElement("div");

This creates a new element node.

Step 3

var InnerDivText = document.createTextNode("Read more about me!");

This creates the text node for the InnerDiv node by using the document.createTextNode() method.

Step 4


This adds the text node InnerDivText as a child of the new InnerDiv using appendChild() DOM node method.

Step 5


This adds the InnerDiv node to the document structure as the last child element of the MeDiv node.

The document structure would look like is shown below.

<div id="div1" title="DanD">
This page is about me!
Read more about me!

When you create complex scripts these properties and methods of the DOM nodes will be very useful.

Leave a Reply