Traversal (Topic)

This topic contains all functions that are directly related to DOM traversal:

Understanding element relationships

The relationships of elements in a DOM tree use terminology of family relationships, with the topmost elements (starting with <html>) considered “older” and the deeper nestled ones “younger” family members.

For example, the following HTML snippet:

  …
    <div> <!-- ancestor -->
      <ul> <!-- parent -->
        <li>…</li> <!-- sibling -->
        <li>…</li> <!-- sibling -->
        <li> <!-- self -->
          <a href="…"> <!-- child -->
            <span>When:
              <time>15:10</time>. <!-- descendant -->
            </span>
          </a>
        </li>
        <li>…</li> <!-- sibling -->
      </ul>
    </div>
  …
Test

When starting from the third <li> element (highlit in the example above), we call:

The four methods in this category allow to traverse the DOM tree in either direction to find related elements.

<HTMLElement>.getAncestors()

The .getAncestors() method returns a list of all direct ancestor elements up to and including the <html> element. The elements are in reverse order, i.e. starting from the immediate parent element and with the <html> element as the last item in the list.

In the above example, this would return a list starting with the <ul> element, then <div> … all the way to <body> and <html>.

<HTMLElement>.getSiblings()

The .getSiblings() method returns a list of all sibling elements.

In the example above, this would return a list of all the <li> elements, excluding the item itself.

<HTMLElement>.getChildren()

The .getChildren() method returns a list of all immediate children elements.

In this example, there is only one child element, which is <a>.

<HTMLElement>.getDescendants()

The .getDescendants() method returns a list of all descendents of the element. This includes the children, the children’s children, and so on.

In the example, this would return a list of <a>, <span> and <time>.

More information