...

/

Navigating the DOM tree

Navigating the DOM tree

Learn about how to navigate and manipulate the DOM tree.

DOM nodes have a number of properties and methods for navigating around the document tree. Once we have a reference to an element, we can walk along the document tree to find other nodes.

Let’s have a look at a couple of the more useful ones.

Child nodes

We can get a collection of all the child elements of an element using the children property. In our food list example, food.children will return a node list of all the child elements of the <ul> element that has an ID of food. These are highlighted in the diagram below.

Press + to interact
Highlighting the three list items that are children of the unordered list
Highlighting the three list items that are children of the unordered list

The code below shows how we can get access to a node list containing the three child <li> elements:

Before we go on, let’s create some references to these child nodes in our program. We’ve added the following code in the index.js file:

const apple = food.children[0];
const banana = food.children[1];
const carrot = food.children[2];
Creating references to child nodes

Parent node

The parentNode property returns the parent node of an element.

The following code returns the food node because it’s the parent of the apple node:

This relationship can be seen in the diagram below:

Press + to interact
The parent node of the apple element is the unordered list element
The parent node of the apple element is the unordered list element

Creating dynamic markup

So far, we’ve looked at how to gain access to different elements of a web page and find out information about them. But the real power of the DOM is ...