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>
      <ul>
        <li></li>
        <li></li>
        <li>
          <a href="…">
            <span>When:
              <time>yesterday</time>.
            </span>
          </a>
        </li>
        <li></li>
      </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.

<HTMLElement>.getSiblings()

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

<HTMLElement>.getChildren()

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

<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.

More information