Selectors & Querying
Relevant source files
The following files were used as context for generating this wiki page:
Selectors and querying form the core interface of Cheerio, providing a jQuery-compatible API to search and filter elements within parsed HTML or XML documents. This system allows developers to navigate complex DOM trees using standard CSS selectors, DOM nodes, or existing Cheerio collections. By wrapping around the cheerio-select engine, the library provides a fast and flexible way to target specific data for extraction or manipulation.
The querying process is typically initiated via the load method, which creates a context-bound selector function (conventionally named $). This function acts as the entry point for all subsequent traversal and selection operations.
Sources: Readme.md:46-55, website/src/lib/docs-nav.ts:25-27
The Selector Function
The primary method for querying is the $(selector, [context], [root]) function. It evaluates the provided selector within a specified scope to return a Cheerio collection.
Selection Parameters
| Parameter | Type | Description |
|---|---|---|
selector | string, DOM Element, Array, Cheerio | The expression or object to search for. |
context | string, DOM Element, Array, Cheerio | (Optional) The scope within which to search. |
root | string, Document | (Optional) The top-level scope, usually the document string. |
Sources: Readme.md:57-65, src/cheerio.spec.ts:48-75
Execution Flow
The following diagram illustrates how a selector is processed to return a collection of elements.
Sources: Readme.md:57-75, src/cheerio.spec.ts:80-95
Supported Selector Types
Cheerio supports a wide array of selector patterns, ranging from basic tag names to complex attribute filters and pseudo-classes.
Basic and Attribute Selectors
- ID and Class:
$('#id'),$('.class'), and multiple classes$('.class1.class2'). - Attributes: Exact match
[attr=val], starts with[attr^=val], ends with[attr$=val], and contains[attr*=val]. - Combinators: Descendant
ul li, immediate childul > li, adjacent sibling.apple + .orange, and general sibling.apple ~ .pear.
Positional and Content Pseudo-classes
Cheerio implements several jQuery-style pseudo-classes to filter collections based on position or content.
| Pseudo-class | Description | Example |
|---|---|---|
:first | Selects the first matched element. | $('li:first') |
:even / :odd | Selects elements by their index parity. | $('li:even') |
:contains(text) | Selects elements containing the specified text. | $('p:contains("Hello")') |
:scope | Refers to the current context. | $(context).find(':scope') |
Sources: src/cheerio.spec.ts:133-165, src/api/traversing.spec.ts:60-80, src/cheerio.spec.ts:200-205
Advanced Querying Methods
Beyond the initial selector function, Cheerio provides chainable methods to refine or expand the search within the DOM tree.
Traversal and Filtering
Methods like .find(), .children(), and .closest() allow for granular navigation through ancestors and descendants.
.find(selector): Searches for matches among the descendants of the current selection..closest(selector): Travels up the DOM tree from the current element to find the nearest ancestor (or itself) that matches the selector..filter(selector/fn): Reduces the current set of elements to those that match the selector or pass a predicate function.
Sources: src/api/traversing.spec.ts:25-50, src/api/traversing.spec.ts:775-800, src/api/traversing.spec.ts:980-1000
Logic Relationship Diagram
This diagram shows the relationship between different traversal directions.
Static Querying Utilities
The cheerio object itself provides static methods for performing operations on DOM nodes without requiring a specific instance context.
cheerio.text(nodes): Extracts the combined text content from the provided nodes.cheerio.html(nodes): Renders theouterHTMLof the provided nodes.cheerio.contains(container, contained): Determines if a node is a descendant of another.
Sources: src/static.spec.ts:50-70, src/static.spec.ts:192-205
Data Extraction Patterns
Newer versions of Cheerio introduce structured querying through the .extract() method. This allows mapping DOM elements to a JavaScript object in a single operation.
const data = $.extract({
items: [{
selector: 'li',
value: {
name: '.title',
link: {
selector: 'a',
value: 'href'
}
}
}]
});
Sources: website/src/content/blog/2024-08-07-version-1.md:37-70, src/static.spec.ts:213-225
In summary, Selectors & Querying in Cheerio provides a robust, jQuery-compatible layer for interacting with DOM structures. By supporting standard CSS selectors, traversal methods, and structured extraction, it enables efficient data processing in server-side and browser environments.