Adding objects

We can add new objects to the DOM by creating new nodes and then inserting them into the existing tree structure. The following methods can be used to create new objects:

Name Meaning
document.createElement("tagname") creates an element node with the specified tag name
document.createTextNode("new text") creates a text node with the specified text content

Once a node has been created, it can be inserted into the tree using one of the methods below. In each of the descriptions, the variable item stores the object that is to be added and parent is its future parent. Notice that each method is called on parent, and that item is one of the parameters.

Name Meaning
.appendChild(item) adds item as the last child of parent
.insertBefore(item, previousChild) inserts item before the child previousChild of parent
.replaceChild(item, oldChild) replaces the child oldChild of parent with item

Order of steps

Best practice suggests that when more than one node is inserted, the element closest to the root of the tree should be created first, with other elements created in order downwards from that node. The nodes should then be attached in the opposite order, so that attachment of nodes closest to the root happens last.

The following set of steps adds a new paragraph with content This is a new paragraph to the end of the document.

var newPara = document.createElement("p");
var newText = document.createTextNode("This is a new paragraph");

newPara.appendChild(newText);
document.body.appendChild(newPara);

Adding a child to newPara takes place before adding a child to the body element, since the body element is closer to the root.