Walking The DOM

The DOM allows us to do anything with elements and their contents, but first we need to reach the corresponding DOM object. All operations on the DOM start with the document object - the main entry point.

DOM nodes

On top: documentElement and body

<html>
  = document.documentElement
  <body>
    = document.body
    <head>
      = document.head
    </head>
  </body>
</html>

document.body can be null

Children: childNodes, firstChild, lastChild

There are 2 terms that we'll use from now on:

childNodes - lists all child nodes, including text nodes
firstChild - gives fast access to the first children
lastChild - gives fast access to the last children

DOM collections

As we can see, childNodes looks like an array. But actually it's not an array, but rather a collection - a special array - like iterable object.

There are 2 important consequences:

Siblings and the parent

Siblings are nodes that are children of the same parent. For instance, <head> and <body> are siblings:

alert(document.body.parentNode === document.documentElement); // true
alert(document.head.nextSibling); // HTMLBodyElement
alert(document.body.previousSibling); // HTMLHeadElement

Element-only navigation

Navigation properties listed above refer to all nodes. But for many tasks we don't want text or comment nodes. We want to manipulate element nodes that represents tags and form the structure of the page.

So let's see more navigation links that only take element nodes into account:

Element nodes

The links are similar to those given above, just with Element word inside:

The <table> element supports (in addition to the given above) these properties:

<thead>, <tfoot>, <tbody> elements provide the rows property:

<tr>:

<td> and <th>:

Searching: getElement*, querySelector*