HTML and CSS Reference
Selecting a set of elements from the DOM is an important step, but is only the first step in
the process. Once a set of elements has been identified a common second step is to traverse
from these elements to another set of elements.
A traversal function always starts with the results of a selection, and then performs a tra-
versal operation on these elements to return a new set of elements.
A common traversal requirement is to traverse from an element, or set of elements, to their
siblings. For instance, in tasks.html input fields and their labels are siblings because they
share the same parent.
Sibling-based queries can be performed through the siblings function. If we want to find all
siblings for the select box with the name of category , we can perform the following query:
If we want to limit the siblings to elements of type label we can add a selector to the siblings
Two other similar functions are next and prev . These return the next and previous sibling
element of the selected element. For instance, the following returns the next sibling of all
labels in the document:
while this returns the previous siblings of all the input fields in the document:
Again, these functions also accept selection criteria if necessary.
Another common traversal requirement is to find specific parents of a given element or set
of elements. For instance, we may wish to find the parent of all input fields. This can be
achieved with the parent function:
We may also wish to limit this to input fields that have div elements as their parents:
A slight variant on this function is the parents function. Instead of returning immediate par-
ents, this returns all ancestors that meet the selection criteria. For instance, the following
returns the section element that is the ancestor of each input field: