Submodule 14.1: Introduction to DOM
Submodule 14.1: Introduction to DOM
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.
Exercise
- Open your editor, create a new file and save it as
exersice14.1.3.html
in the folder "yourNameWEB2JS". - Copy the code below and paste it in the new file.
- Open the console to see the results.
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]
- Modify the above code to determine the console.log outputs of the ul tag.
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.