Register to get access to free programming courses with interactive exercises

Navigating the DOM Tree JS: DOM API

Studying the structure of DOM trees is the easiest way to get acquainted with them.

In short, DOM trees consist of nodes, which form a hierarchy similar to HTML. Some nodes are leaf nodes, so they don't contain other nodes inside themselves. Some nodes are internal, so they have children.

Specific nodes most often describe specific tags from HTML and contain their attributes inside themselves. Nodes have a type that defines a set of node properties and methods. In this lesson, we will get to know them below.

The root element in the DOM tree corresponds to the <html> tag.

You can access it like this:

const html = document.documentElement;
// The node's tag `Name property` contains the name of the tag in uppercase
console.log(html.tagName); // => 'HTML'

// There is HTML tag content in DOM tree nodes
// The text is also represented by a node because the head is higher than the body
html.childNodes; // [head, text, body]

html.firstChild; // <head>...</head>
html.lastChild; // <body>...</body>

// It's the second child, called by the index
html.childNodes[1]; // #text

Since <body> and <head> are always present inside the document, we can move them to the document object level for easier access:

document.head;
document.body;

You can go both up and down the tree:

// The parent of the body is HTML
document.documentElement === document.body.parentNode; // true
document.body === document.body.childNodes[2].parentNode; // true

Essentially, if you imagine a tree, you can move up to the parent, down to the child, and left and right to the siblings.

childNodes

We can use the property childNodes to get children — nodes nested in the current node on one level of nesting. Also, you can use the term descendants of the first level.

There are several interesting points to note while working with childNodes:

  1. This property is read-only. Trying to write something to a specific element won't work:

    // There'll be no error, but nothing will change
    document.body.childNodes[0] = 'hey';
    

    To change DOM trees we have to use a specific set of methods. We will discuss them in the corresponding lesson.

  2. Although childNodes returns a set of elements, it's still not an array. It lacks the usual methods, such as map(), filter(), and others. However, it does have forEach():

    // NodeList type
    const nodes = document.documentElement.childNodes;
    
    nodes.forEach((el) => console.log(el));
    

    If you want to, you can convert it into an array and then work with it in the usual way:

    const list = Array.from(nodes);
    // Now we have a regular array
    // There are methods available, for example, filter
    // We can filter the elements we need
    const filtered = list.filter((item) => item.textContent.includes('Navigating the DOM Tree'));
    // and extract data from them, such as tag names
    const filteredTags = filtered.map((item) => item.tagName);
    console.log(filteredTags); // => 'HEAD', 'BODY']
    

Hierarchy

The nodes in the DOM tree not only have types, but they also build a hierarchy.

In the hierarchy, subtypes inherit the properties and methods of their parent types and add their specific ones:

DOM Tree

// The easiest way to view the type
document.body.toString(); // "[object HTMLBodyElement]"
document.body instanceof HTMLBodyElement; // true

Nodes with the text and comment types are leaf nodes, meaning they cannot have children. But element types are what we deal with most often. The elements include all types represented by tags in HTML.

Whenever you work with a tree, you can expect to see children and descendants. Concerning the DOM tree, this means that the tag has a body, children, and descendants. How do they differ from each other?

const html = `
  <html>
    <head></head>
    <body>
      <div id="parent-div">
        <h1>Header</h1>
        Hello!
        <div class="child-div">
          <span>Some <b>text</b></span>
          <ol>
            <li>1</li>
            <li>2</li>
          </ol>
          <!-- End List -->
        </div>
      </div>
    </body>
  </html>
`;

The<div> tag with id parent-div contains three child nodes and 14 descendants. Why?

Child nodes: <h1>, text "Hello!" and <div> with thechild-div class.

Concerning the node, children are only those nodes that lie directly in it, at the first level of nesting.

Descendants are all nodes nested in it at all levels of nesting. The descendants of the <div> with id parent-div, in addition to the above three child tags, are also all nodes nested in these child tags (as well as nodes nested in these nested nodes and so on, given the recursive nature of trees).

Child nodes are also descendants. However, this isn't the same the other way round: the descendant is not necessarily a child element (in the example, the tag <span> is a descendant, but not a child to the <div> with id parent-div).

Elements

Usually, it's elements we're interested in, not just any nodes. It's elements that we want to manipulate and move through. This is so important that the DOM has an alternative way of traversing the tree, built only on elements:

Relationships between elements in the DOM tree

All these methods return Element type objects and skip Text and Comment objects. You can see it in the example below, where the children property returns only tags. This is how children differs from childNodes, which returns all nodes, including leaf nodes:

const node = document.documentElement;
node.children; // [head, body]

There is another difference between children and childNodes. They return not only a different set of nodes but also different types of collections:

  • childNodes returns a NodeList
  • children returns an HTML collection

They work a little differently, but we will look at the difference later when we get acquainted with selectors.

Special navigation

Some elements, such as forms and tables, have specific properties for navigating through them:

<table>
  <tr>
    <td>1.1</td>
    <td>1.2</td>
    <td>1.3</td>
  </tr>
  <tr>
    <td>2.1</td>
    <td>2.2</td>
    <td>2.3</td>
  </tr>
</table>
const table = document.body.firstElementChild
table.rows[0].cells[2];

This method of navigation does not replace the main ones. It's made solely for convenience in places where it makes sense.

Conclusion

Do we need to know all these methods by heart? Actually, no. It's important to understand the general principles of DOM tree structure. Also, you should know the hierarchy of types and the basics of traversing through elements. But that's all for now.

You can always read about specific methods and properties in the documentation. Not so many people remember them by heart, and there are no practical reasons to do so.

In addition, traversing through trees in these ways is a low–level way of working. The main way to select the elements is through selectors, which we will discuss later.


Do it yourself

  1. Open the console in your browser.
  2. Starting from document.body get to the deepest nodes containing this text.

Recommended materials

  1. Node

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.