Changing Documents
Now that we’ve looked at how we can extract information from our documents using the DOM, we probably want to be able to change them. There are really just a few things we need to know to make changes, so we describe the basic operations and then show a few examples. The basic operations involved in modifying a document center around creating new nodes, adding, moving, and removing nodes, and modifying the contents of nodes. Since we often want to add new elements and textual content, we start by looking at creating new nodes.
Creating New Nodes
Most of the time, new nodes need to be created explicitly. Since the DOM is defined as a set of interfaces rather than as concrete classes, the only way to create new nodes is to make call methods on the objects we already have in hand. Fortunately, the Document interface includes a large selection of factory methods we can use to create new nodes of most types. (Methods for creating entity and notation nodes are noticeably absent, but most applications should not find themselves constrained by that.)
The most used of these factory methods are very simple, and are
used to create new element and text nodes. For elements, use the
createElement method, with the tag
name of the element to create as the only parameter. Text nodes can be
created using the createTextNode
method, passing the text of the new node as the parameter. For the
details on the other node factory methods, see the reference material
in Appendix D.