Lesson 4 of 6

How DOM nodes link together

Tree links are object references, nothing more.

The document "tree" is really thousands of plain object properties pointing at each other: parentNode points up, childNodes points down, nextSibling points across. These links are structure and they change every time the page changes. They are completely independent from the prototype links of lessons 1–3, which describe behavior and almost never change. Below, both graphs are shown for the same objects.

The classic traps

childNodes vs children

childNodes includes every node: elements, text (even pure whitespace), and comments. children includes elements only. Select the ul above and compare the two rows.

nextSibling vs nextElementSibling

nextSibling frequently lands on an invisible whitespace text node. nextElementSibling skips to the next element. Select the first li above and check both rows.

Links are live

Removing a node with node.remove() just rewires these references: the node still exists as an object (with all its prototype behavior), it simply has parentNode === null until re-inserted somewhere.

Everything reaches everything

From any node you can reach the whole world: node.ownerDocument is the document, document.defaultView is window, and window holds every constructor. That global object is Lesson 5.