Customized Web Tools and Tutorials JSWorks

Working with Nodes

Understanding the Node Tree

JavaScript organizes an HTML document in a tree structure known as a node tree. Each HTML element, comment, and text string is stored within the tree as a separate node.

The box on the right shows the node tree for this article. Note that line returns and blank spaces between element tags are counted as text nodes and appear in the node tree as white space nodes. In this article there are total nodes, comprised of element nodes, and text nodes (containing white space nodes).

The Familial Relationship of Nodes

Nodes in the node tree have a familial relationship, where each node acts as a parent, child, and sibling of other nodes. This relationship is expressed using the form

node.relationship

where node is a currently selected node or object and relationship is the relationship of another node to the current node. For example, the expression

node.parentNode

refers to the parent of node. In an HTML document the parent of the body node is the html node, and the parent of the html node is the document node, which represents the entire document. The table below describes the other familial relationships under the document object model.

Expression Description
node.firstChild The first child of node.
node.lastChild The last child of node.
node.childNodes A collection of all of the nodes contained within node.
node.previousSibling The sibling prior to node.
node.nextSibling The sibling after node.
node.ownerDocument The root node of the document
node.parentNode The parent of node.

Node Types, Names, and Values

JavaScript provides the following properties to determine each node's type, name, and value:

node.nodeType
node.nodeName
node.nodeValue

The nodeType property returns an integer indicating whether the node refers to an element, a text string, a comment, an attribute, and so on. The nodeName property returns the name of the node within the document. Finally, the nodeValue property returns the node's value.