Nodes and Dom traversing

Every object on the DOM tree is a node and elements are a specific type of node.

There are 12 types of nodes which you can find here.

The ones that you will often encounter are: element, attribute and text.

Knowing the node type is essential to be able to determine which properties you can use.

In the below code you will see how you can determine the node type and also distinguish between the children and childnodes.

Only elements can have children, however, nodes can have childnodes. 

Code:

Exercise

    1. Open your editor, create a new file and save it as exersice14.1.3.html in the folder "yourNameWEB2JS".
    2. Copy the code below and paste it in the new file.
    3. Open the console to see the results.

Answer:

The node type of document is: 9 The node type of H1 is: 1
The length of childNodes of H1 is: 1
The length of children of H1 is: 0
The next slibing of H1: [object Text]
The parentElement of H1: [object HTMLDivElement]
    1.  Modify the above code to determine the console.log outputs of the ul tag.

Answer:

The node type of document is: 9
The node type of ul is: 1
The length of childNodes of ul is: 7
The length of children of ul is: 3
The next slibing of ul: [object Text]
The parentElement of ul: [object HTMLDivElement]

Two things to note from the above example. First, that the console returns us the number of the nodeType as it is determined on the w3schools link above. Also, although in this case <h1> doesn't have children, it has 1 childnode which is the text that it contains.

With the above knowledge, you are now ready to get a first idea of how we can access the different nodes, a process that is known as traversing the DOM. Visit the Walking the DOM page to understand the properties that link nodes to other nodes.