libs: - d3 - domtree --- # 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. That's the main "entry point" to DOM. From it we can access any node. Here's a picture of links that allow for travel between DOM nodes: ![](dom-links.svg) Let's discuss them in more detail. ## On top: documentElement and body The topmost tree nodes are available directly as `document` properties: `` = `document.documentElement` : The topmost document node is `document.documentElement`. That's the DOM node of the `` tag. `` = `document.body` : Another widely used DOM node is the `` element -- `document.body`. `` = `document.head` : The `` tag is available as `document.head`. ````warn header="There's a catch: `document.body` can be `null`" A script cannot access an element that doesn't exist at the moment of running. In particular, if a script is inside ``, then `document.body` is unavailable, because the browser did not read it yet. So, in the example below the first `alert` shows `null`: ```html run ``` ```` ```smart header="In the DOM world `null` means \"doesn't exist\"" In the DOM, the `null` value means "doesn't exist" or "no such node". ``` ## Children: childNodes, firstChild, lastChild There are two terms that we'll use from now on: - **Child nodes (or children)** -- elements that are direct children. In other words, they are nested exactly in the given one. For instance, `` and `` are children of `` element. - **Descendants** -- all elements that are nested in the given one, including children, their children and so on. For instance, here `` has children `
` and `