Home Page -> DOM Tutorials -> Using Events -> About Nodes

About Nodes

As we detailed in a previous article, your documents are made up of “spare parts” that are nested inside one another. The HTML at the right has this structure:

  • A <body>, which contains
    • A paragraph (<p>), which contains
      • the First Text
      • an image (<img>)
      • and an italic (<i>) element which contains
        • More Text
<body>
<p>
   First Text
   <img src="picture.png">
   <i>More Text</i>
</p>
</body>

When CSS-compliant browsers read your HTML files, they analyze this structure and create a structure of nodes, which you can think of as little chunks of information that describe your document. The nodes for the HTML at the right can be diagrammed like this: [To save space, we've shown only some of the information in each node.]

tree diagram

Nodes also contain information about their relationship to each other. Let's look at node B as if it were a member of a family tree. Node B's parentNode is node A. Node B's firstChild is node C, and its lastChild is node E. (Node B also contains a childNodes array that lists all its immediate children, C, D, and E).

Node D has a previousSibling, which is node C, and a nextSibling, node E. Since node C has nobody to its left and nobody immediately below it, its previousSibling and firstChild properties will both be null.

We're going to use the ability to move through this “family tree” of a document's nodes to find out which <div> a user clicked in the expanding menu.

For a quick quiz on nodes, see if you can answer these questions:

  1. Who is node F's parentNode?
  2. Who is node A's firstChild?
  3. Who are node B's nextSibling and previousSibling?
See the answers
  1. Node E is node F's parent.
  2. Node B is A's firstChild (and also its lastChild).
  3. Node B is an only child, so its previousSibling and nextSibling are null.

  Setting Events  Index Finding the div