This topic contains all functions that are directly related to DOM traversal:
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> …
When starting from the third <li> element (highlit in the example above), we call:
<li> item that we start from: self<li> items that are on the same level as the self item as siblings<html> element, are its ancestorsThe four methods in this category allow to traverse the DOM tree in either direction to find related elements.
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>.
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.
The .getChildren() method returns a list of all immediate children elements.
In this example, there is only one child element, which is <a>.
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>.