6.4 Creating New Nodes

The base of the entire tree is the Document node. Its documentElement attribute contains the Element node for the root element. The Document node may have additional children, such as ProcessingInstruction nodes, but the list of children can include at most one Element node.

When building a DOM tree from scratch, you'll need to construct new nodes of various types such as Element and Text. The Document node has a bunch of create*() methods such as createElement and createTextNode().

For example, here's an example that adds a new child element named "chapter" to the root element.

new = document.createElement('chapter')
new.setAttribute('number', '5')
document.documentElement.appendChild(new)