Adding objects
We can add new objectsA "bundle" of values. to the DOM by creating new nodesA part of a tree. and then inserting them into the existing tree structure. The following methodsA function associated with a class. can be used to create new objects:
Name | Meaning |
---|---|
document.createElement("tagname") |
creates an element nodeA node in the DOM for an element. with the specified tag name |
document.createTextNode("new text") |
creates a text nodeA node in the DOM for the text inside an element. 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 rootA node without a parent. 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.