6.3 Manipulating the Tree

We'll start by considering the basic Node class. All the other DOM nodes--Document, Element, Text, and so forth--are subclasses of Node. It's possible to perform many tasks using just the interface provided by Node.

First, there are the attributes provided by all Node instances:

Attribute  Meaning 
nodeType Integer constant giving the type of this node: ELEMENT_NODE, TEXT_NODE, etc.
nodeName Name of this node. For some types of node, such as Elements, the name is the element name; for others, such as Text, the name is a constant value such as "#text" which isn't very useful.
nodeValue Value of this node. For some types of node, such as Text nodes, the value is a string containing a chunk of textual data; for others, such as Text, the value is just None.
parentNode Parent of this node, or None if this node is the root of a tree (usually meaning that it's a Document node).
childNodes A possibly empty list containing the children of this node.
firstChild First child of this node, or None if it has no children.
lastChild Last child of this node, or None if it has no children.
previousSibling Preceding child of this node's parent, or None if this node has no parent or if the parent has no preceding children.
nextSibling Following child of this's node's parent, or None if this node has no parent or if the parent has no following children.
ownerDocument Owning document of this node.
attributes A NamedNodeMap instance that behaves mostly like a dictionary, and maps attribute names to Attribute instances.

Next, there are the methods. If a node is already a child of node 1 and is added as a child of node 2, it will automatically be removed from node 1; nodes always have exactly zero or one parents.

Method  Effect 
appendChild(newChild) Add newChild as a child of this node, adding it to the end of the list of children.
removeChild(oldChild) Remove oldChild; its parentNode attribute will now return None.
replaceChild(newChild, oldChild Replace the child oldChild with newChild. oldChild must already be a child of the node.
insertBefore(newChild, refChild) Add newChild as a child of this node, adding it before the node refChild. refChild must already be a child of the node.
hasChildNodes() Returns true if this node has any children.
cloneNode(deep) Returns a copy of this node. If deep is false, the copy will have no children. If it's true, then all of the children will also be copied and added as children to the returned copy.

Element nodes and the Document node also have a useful method, getElementsByTagName(tagName), that returns a list of all elements with the given name. For example, all the "chapter" elements can be returned by document.getElementsByTagName('chapter').