libs: - d3 - domtree --- # Walking the DOM DOM allows to do anything with elements and their contents, but first we need to reach the corresponding DOM object, get it into a variable, and then we are able to modify it. All operations on DOM start with the `document` object. From it we can access any node. [cut] Here's a picture of links that allow to travel between DOM nodes: ![](dom-links.png) 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 DOM node of `` 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 `