Trees and Nodes

Each HTML element is called a node in the DOM structure. Nested elements are called children of a node. Nodes can refer to other nodes and all nodes branch out from the root of the DOM, which is the html element, accessible through document.documentElement. This kind of structure is called a tree structure. It resembles a tree where branches and nodes grow from the root with leaves at the end of a path.

There are 12 types of DOM nodes. And they are represented by a number value which you can access through the nodeType property. Regular HTML elements are called "ELEMENT_NODE" with the NodeType number 1. A text node has nodeType of 3, it is also defined by the constant property document.TEXT_NODE. A comment has the nodeType of 8. The document itself is also a node and has nodeType 9.

console.log(document.nodeType);
// -> 9
console.log(document.body.nodeType);
// -> 1

We can print out the nodeType of each element inside the document.body in our example HTML from the previous page with a small bit of code.

<!doctype html>
<html>
  <head>
    <title>My title</title>
  </head>
  <body>
    <h1>A heading</h1>
    <a href="www.altcademy.com">Link text</a>
    <script src="index.js"></script>
  </body>
</html>
var printNodeTypes = function () {
  var children = document.body.childNodes;
  for (i = 0; i < children.length; i++) {
    console.log(children[i].nodeType + ": " + children[i].nodeName);
  }
}
printNodeTypes();

// -> 3: #text
// -> 1: H1
// -> 3: #text
// -> 1: A
// -> 3: #text
// -> 1: SCRIPT

Try it out on Repl.

Whitespace inside elements is considered as text. That's why you see the first element being printed is a text node, it is due to the new line character after the opening <body> tag. There are also text nodes between each element node, due to the new line character.

The other node types are not very useful for this course or the majority of web development in general, and 5 of them have been deprecated in the new DOM4 specification. You can have a look at those on MDN.

You can visualize the DOM structure as a tree growing sideways with the following illustration.

Tree and Nodes wikipedia

As we have seen, DOM nodes are basically JavaScript objects. Following that trail of thought, the childNodes property should be an Array object. But it's not, it's an array like object called NodeList. It has a length property, methods such as forEach, keys, values but it doesn't have methods such as slice or push. Standards of the DOM structure isn't the most well designed, so there are some getchas that we just have to watch out for when manipulating the DOM. Don't worry, most of them are simply nuisances.

results matching ""

    No results matching ""