Traversing the DOM
Relevant source files
The following files were used as context for generating this wiki page:
Traversing the DOM in Cheerio involves navigating through the document structure to locate, filter, and interact with specific nodes. This system implements a subset of the core jQuery API, optimized for server-side performance and flexibility. It allows developers to move between parents, children, and siblings, or find descendants using CSS selectors within a defined context.
The traversal API operates on a consistent DOM model derived from domhandler, providing a reliable way to interact with parsed HTML or XML. By utilizing a stack-based approach for some operations, Cheerio also supports "chaining" and returning to previous selection states using methods like .end().
Sources: Readme.md:46-51, src/api/traversing.spec.ts:1095-1150
Core Selection and Navigation
The entry point for most traversal is the primary selector function, which allows searching within a specific scope.
The Selector Function
The $( selector, [context], [root] ) method is the primary tool for selecting elements. It can accept string expressions, DOM elements, or other Cheerio objects. If a context is provided, the search is restricted to descendants of that context.
Sources: Readme.md:76-85, src/cheerio.spec.ts:63-100
Movement Methods
Cheerio provides specialized methods for moving to adjacent or related nodes in the DOM tree.
| Method | Description |
|---|---|
.find(selector) | Searches for descendants matching the selector within the current selection. |
.children([selector]) | Gets the immediate children of each element in the set, optionally filtered by a selector. |
.parent([selector]) | Gets the immediate parent of each element in the set. |
.parents([selector]) | Gets all ancestors of each element in the set, up to the root. |
.siblings([selector]) | Gets all siblings of each element in the set. |
.next() / .prev() | Gets the immediately following or preceding sibling. |
Sources: src/api/traversing.spec.ts:32-35, src/api/traversing.spec.ts:167-170, src/api/traversing.spec.ts:646-650, src/api/traversing.spec.ts:718-722, src/api/traversing.spec.ts:544-548
Positional and Functional Filtering
Filtering allows developers to refine a selection set based on position, attributes, or custom logic.
Positional Filtering
Elements can be selected based on their index within the current Cheerio collection.
This diagram shows the relationship between positional methods and the resulting collections.
Sources: src/api/traversing.spec.ts:1015-1025, src/api/traversing.spec.ts:983-990, src/api/traversing.spec.ts:1062-1070
Logic-Based Filtering
.filter(selector\|fn): Reduces the set to those that match a selector or pass a function's test..not(selector\|fn): The inverse of filter; removes elements that match the criteria..has(selector\|node): Filters the set to elements that have a descendant matching the input..is(selector\|node\|fn): Checks if at least one element in the selection matches the criteria, returning a boolean.
Sources: src/api/traversing.spec.ts:900-915, src/api/traversing.spec.ts:938-950, src/api/traversing.spec.ts:1290-1300
Hierarchy and Relationship Traversal
Navigating the vertical and horizontal axes of the DOM tree is performed through "Until" methods and ancestral lookups.
Ancestral Navigation
Methods like .closest(selector) search up through the element and its ancestors in the DOM tree until a match is found.
This diagram illustrates the "upward" search logic of the .closest() method.
Sources: src/api/traversing.spec.ts:771-785
Sibling Range Navigation
The "Until" family of methods allows selecting a range of siblings or parents up to, but not including, a specific marker.
.nextUntil([selector]): Siblings following the element..prevUntil([selector]): Siblings preceding the element..parentsUntil([selector]): Ancestors up to the match.
Sources: src/api/traversing.spec.ts:326-335, src/api/traversing.spec.ts:488-500, src/api/traversing.spec.ts:586-600
Iteration and Transformation
Cheerio provides methods to iterate over collections or transform them into new formats.
.each(fn): Executes a function for each element in the collection. Returningfalsebreaks the loop..map(fn): Passes each element through a function, producing a new Cheerio object containing the return values..get([index]): Retrieves the underlying DOM nodes. If an index is provided, returns a single node; otherwise, returns an array of all nodes.
Sources: src/api/traversing.spec.ts:810-825, src/api/traversing.spec.ts:845-860, src/api/traversing.spec.ts:1030-1045
The Traversal Stack and Chaining
Cheerio maintains a "prevObject" stack that allows developers to revert to a previous state in a chain of commands.
Using .end()
The .end() method pops the current selection off the stack and returns the previous selection. This is useful when performing multiple operations on different parts of a tree within a single chain.
$('#fruits')
.find('.apple')
.addClass('selected')
.end() // Returns to #fruits
.find('.orange')
.addClass('next-target');
Sources: src/api/traversing.spec.ts:1095-1148
Combining Sets with .add()
The .add() method creates a new Cheerio object with elements added to the existing set. It ensures document order and uniqueness (no duplicates).
Sources: src/api/traversing.spec.ts:1152-1170
Summary of Traversing the DOM
Traversing the DOM in Cheerio provides a robust, jQuery-compatible interface for navigating complex HTML and XML structures. By combining vertical movement (parents/children), horizontal movement (siblings), and complex filtering (selectors/functions), it enables precise node targeting. The implementation of the traversal stack via .end() and .addBack() further supports elegant, chainable code structures required for efficient document manipulation and data extraction.