Cheerio API Reference
Cheerio is a fast, flexible, and elegant server-side implementation of core jQuery functionality. It provides a familiar jQuery-like API for parsing and manipulating HTML and XML documents in Node.js environments.
Core Loading Functions
cheerio.load(content, options?)
Loads HTML/XML content and returns a CheerioAPI instance for querying and manipulation.
Signature:
function load(
content: string | AnyNode | AnyNode[] | Buffer,
options?: CheerioOptions,
isDocument?: boolean
): CheerioAPI
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
content |
string | AnyNode | AnyNode[] | Buffer |
- | HTML/XML content to parse |
options |
CheerioOptions |
{} |
Parser and behavior options |
isDocument |
boolean |
true |
Whether to treat content as a complete document |
Returns: CheerioAPI - A Cheerio instance with jQuery-like methods
Examples:
import * as cheerio from 'cheerio';
// Basic HTML loading
const $ = cheerio.load('<ul><li>Apple</li><li>Orange</li></ul>');
// With options
const $ = cheerio.load('<xml><item>data</item></xml>', {
xmlMode: true,
decodeEntities: false
});
// Loading from buffer
const buffer = Buffer.from('<div>Hello</div>');
const $ = cheerio.load(buffer);
Common gotchas:
- XML mode must be explicitly enabled for XML documents
- By default, HTML5 parser rules apply (self-closing tags, etc.)
- Buffer encoding is automatically detected but may need explicit specification
Element Selection
$(selector, context?, root?)
Selects elements from the loaded document using CSS selectors, similar to jQuery's $() function.
Signature:
function $(
selector: string | AnyNode | AnyNode[] | Cheerio<AnyNode>,
context?: string | AnyNode | Cheerio<AnyNode>,
root?: string | Document
): Cheerio<Element>
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
selector |
string | AnyNode | AnyNode[] | Cheerio<AnyNode> |
- | CSS selector or elements to select |
context |
string | AnyNode | Cheerio<AnyNode> |
document |
Context to search within |
root |
string | Document |
- | Root document for context |
Returns: Cheerio<Element> - Collection of matched elements
Examples:
// Basic selection
$('li').length; // Number of <li> elements
$('.apple').text(); // Text content of first element with class 'apple'
// With context
$('li', '#fruits').addClass('fruit'); // Find <li> within #fruits
// Complex selectors
$('li:nth-child(2n)').css('color', 'red'); // Every other <li>
$('a[href^="https://"]').attr('target', '_blank'); // External links
Attribute Manipulation
.attr(name, value?)
Gets or sets attributes on the matched elements.
Signature:
// Get attribute
function attr(name: string): string | undefined;
// Set attribute
function attr(name: string, value: string | null | ((i: number, attr: string) => string | null)): Cheerio<T>;
// Set multiple attributes
function attr(attributes: Record<string, string | null>): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
name |
string | Record<string, string | null> |
- | Attribute name or object map |
value |
string | null | function |
- | Value to set, null to remove, or function |
Returns: string \| undefined \| Cheerio<T> - Attribute value (getter) or Cheerio instance (setter)
Examples:
// Get attribute
const href = $('a').attr('href'); // Gets href of first <a>
// Set attribute
$('img').attr('alt', 'Description'); // Sets alt text
$('a').attr('href', null); // Removes href attribute
// Multiple attributes
$('input').attr({
type: 'text',
placeholder: 'Enter name',
required: 'required'
});
// Function-based setting
$('img').attr('src', (i, src) => src.replace('http://', 'https://'));
Common gotchas:
- Setting attribute to
nullremoves it entirely - Boolean attributes return their name when present (
'checked'), nottrue - Functions receive index and current value as parameters
.prop(name, value?)
Gets or sets properties on DOM elements, handling special properties like checked, selected, etc.
Signature:
// Get property
function prop(name: string): any;
// Set property
function prop(name: string, value: any): Cheerio<T>;
// Set multiple properties
function prop(properties: Record<string, any>): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
name |
string | Record<string, any> |
- | Property name or object map |
value |
any |
- | Value to set |
Returns: any \| Cheerio<T> - Property value (getter) or Cheerio instance (setter)
Examples:
// Get property
const isChecked = $('input[type="checkbox"]').prop('checked'); // true/false
// Set property
$('input[type="checkbox"]').prop('checked', true);
$('option').prop('selected', false);
// Special properties
$('a').prop('href'); // Resolved absolute URL
$('div').prop('outerHTML'); // Full HTML including the element
$('div').prop('innerHTML'); // Inner HTML content
.data(key, value?)
Gets or sets data attributes with automatic type conversion for HTML5 data-* attributes.
Signature:
// Get all data
function data(): Record<string, unknown>;
// Get specific data
function data(key: string): unknown;
// Set data
function data(key: string, value: unknown): Cheerio<T>;
// Set multiple data
function data(values: Record<string, unknown>): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
key |
string | Record<string, unknown> |
- | Data key or object map |
value |
unknown |
- | Value to set |
Returns: unknown \| Record<string, unknown> \| Cheerio<T> - Data value or Cheerio instance
Examples:
// HTML: <div data-user-id="123" data-active="true">
const userId = $('.user').data('userId'); // 123 (number)
const isActive = $('.user').data('active'); // true (boolean)
// Set data
$('.user').data('lastSeen', new Date());
$('.user').data({
role: 'admin',
permissions: ['read', 'write']
});
// Camel case conversion
$('<div data-foo-bar="test">').data('fooBar'); // "test"
Common gotchas:
- Data attributes are automatically parsed (JSON, numbers, booleans)
- Camel case keys map to hyphenated data attributes
- Data set via
.data()doesn't update the actual HTML attribute
Content Manipulation
.text(value?)
Gets or sets the text content of elements, stripping all HTML tags.
Signature:
// Get text
function text(): string;
// Set text
function text(value: string | number | ((i: number, text: string) => string | number)): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
value |
string | number | function |
- | Text content to set or function |
Returns: string \| Cheerio<T> - Text content (getter) or Cheerio instance (setter)
Examples:
// Get text content
const title = $('h1').text(); // "Welcome to My Site"
// Set text (HTML-safe)
$('h1').text('New <Title>'); // Displays: "New <Title>" (not rendered as HTML)
// Function-based setting
$('li').text((i, currentText) => `${i + 1}. ${currentText}`);
.html(value?)
Gets or sets the inner HTML content of elements.
Signature:
// Get HTML
function html(): string | null;
// Set HTML
function html(value: string | ((i: number, html: string) => string)): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
value |
string | function |
- | HTML content to set or function |
Returns: string \| null \| Cheerio<T> - HTML content (getter) or Cheerio instance (setter)
Examples:
// Get HTML
const content = $('.container').html(); // "<p>Hello <strong>world</strong></p>"
// Set HTML
$('.container').html('<p>New content</p>');
// Function-based setting
$('div').html((i, oldHtml) => `<span>Item ${i}</span>${oldHtml}`);
Common gotchas:
.html()returns inner HTML, use.prop('outerHTML')for the complete element- Setting HTML overwrites all existing content
- HTML is not sanitized - be careful with user input
.val(value?)
Gets or sets the value of form elements (input, select, textarea).
Signature:
// Get value
function val(): string | string[] | undefined;
// Set value
function val(value: string | string[]): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
value |
string | string[] |
- | Value to set (array for multi-select) |
Returns: string \| string[] \| undefined \| Cheerio<T> - Form value or Cheerio instance
Examples:
// Get values
const inputValue = $('input[name="email"]').val(); // "user@example.com"
const selectedOptions = $('select[multiple]').val(); // ["option1", "option2"]
// Set values
$('input[type="text"]').val('New value');
$('select[multiple]').val(['option1', 'option3']); // Selects multiple options
$('textarea').val('Long text content...');
DOM Manipulation
.append(content)
Inserts content as the last child of each matched element.
Signature:
function append(
...contents: (
| string
| AnyNode
| AnyNode[]
| Cheerio<AnyNode>
| ((i: number, html: string) => string | AnyNode | Cheerio<AnyNode>)
)[]
): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
contents |
string | AnyNode | Cheerio | function |
- | Content to append |
Returns: Cheerio<T> - The original Cheerio instance
Examples:
// Append HTML string
$('ul').append('<li>New item</li>');
// Append multiple items
$('ul').append('<li>Item 1</li>', '<li>Item 2</li>');
// Append Cheerio object
const $newLi = $('<li>').text('Dynamic item');
$('ul').append($newLi);
// Function-based appending
$('div').append((i, html) => `<p>Section ${i + 1}</p>`);
.remove(selector?)
Removes matched elements from the DOM.
Signature:
function remove(selector?: string): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
selector |
string |
- | Optional selector to filter removal |
Returns: Cheerio<T> - The removed elements
Examples:
// Remove all matched elements
$('.obsolete').remove();
// Remove with filtering
$('li').remove(':contains("delete")'); // Remove <li> containing "delete"
// Chain after removal
$('p').remove().appendTo('.archive'); // Move to archive
CSS and Styling
.css(property, value?)
Gets or sets CSS styles on elements.
Signature:
// Get style
function css(property: string): string | undefined;
// Set style
function css(property: string, value: string | ((i: number, style: string) => string)): Cheerio<T>;
// Set multiple styles
function css(properties: Record<string, string>): Cheerio<T>;
// Get multiple styles
function css(properties: string[]): Record<string, string>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
property |
string | string[] | Record<string, string> |
- | CSS property name, array, or object |
value |
string | function |
- | CSS value to set or function |
Returns: string \| Record<string, string> \| Cheerio<T> - CSS value(s) or Cheerio instance
Examples:
// Get computed style
const color = $('.highlight').css('color'); // "red"
// Set single style
$('.box').css('background-color', 'blue');
// Set multiple styles
$('.card').css({
'border-radius': '8px',
'box-shadow': '0 2px 4px rgba(0,0,0,0.1)',
padding: '16px'
});
// Function-based setting
$('div').css('width', (i, width) => `${parseInt(width) + 10}px`);
.addClass(className)
Adds CSS class(es) to matched elements.
Signature:
function addClass(
className: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
className |
string | function |
- | Space-separated class names or function |
Returns: Cheerio<T> - The Cheerio instance for chaining
Examples:
// Add single class
$('.item').addClass('active');
// Add multiple classes
$('.card').addClass('highlighted featured');
// Function-based adding
$('li').addClass((i, currentClass) => {
return i % 2 === 0 ? 'even' : 'odd';
});
.removeClass(className?)
Removes CSS class(es) from matched elements.
Signature:
function removeClass(
className?: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
className |
string | function |
- | Classes to remove, or function (omit to remove all) |
Returns: Cheerio<T> - The Cheerio instance for chaining
Examples:
// Remove specific class
$('.item').removeClass('active');
// Remove multiple classes
$('.card').removeClass('highlighted featured');
// Remove all classes
$('.temp').removeClass();
// Function-based removal
$('div').removeClass((i, currentClass) => {
return currentClass.includes('temp-') ? currentClass : '';
});
.hasClass(className)
Checks if any matched element has the specified CSS class.
Signature:
function hasClass(className: string): boolean;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
className |
string |
- | Class name to check |
Returns: boolean - True if any element has the class
Examples:
// Check for class
if ($('.nav-item').hasClass('active')) {
console.log('Found active navigation item');
}
// Conditional logic
$('.button').each(function() {
if ($(this).hasClass('primary')) {
$(this).css('font-weight', 'bold');
}
});
Traversal and Filtering
.find(selector)
Searches for descendant elements matching the selector.
Signature:
function find<T extends AnyNode>(selector: string): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
selector |
string |
- | CSS selector to search for |
Returns: Cheerio<T> - Collection of found descendant elements
Examples:
// Find descendants
const links = $('.nav').find('a'); // All <a> tags inside .nav
// Complex selectors
const activeLinks = $('.menu').find('li.active a[href]');
// Chain with other methods
$('.article').find('img').attr('loading', 'lazy');
.each(callback)
Iterates over matched elements, executing a callback for each.
Signature:
function each(
callback: (this: T, i: number, el: T) => void | false
): Cheerio<T>;
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
callback |
function |
- | Function to execute for each element |
Returns: Cheerio<T> - The original Cheerio instance
Examples:
// Basic iteration
$('li').each(function(i, el) {
console.log(`Item ${i}: ${$(el).text()}`);
});
// Early termination
$('.item').each(function(i) {
if ($(this).hasClass('stop')) return false; // Break loop
$(this).addClass(`item-${i}`);
});
// Arrow function (note: `this` context differs)
$('img').each((i, img) => {
$(img).attr('alt', `Image ${i + 1}`);
});
Common gotchas:
- Return
falsefrom callback to break the loop early - Arrow functions don't bind
thisto the current element - Index parameter is zero-based
Form Handling
.serialize()
Serializes form elements into a URL-encoded query string.
Signature:
function serialize(): string;
Returns: string - URL-encoded form data
Examples:
// Serialize entire form
const formData = $('form').serialize();
// "name=John&email=john%40example.com&subscribe=on"
// Serialize specific inputs
const inputData = $('input[type="text"], select').serialize();
.serializeArray()
Serializes form elements into an array of name-value objects.
Signature:
function serializeArray(): Array<{ name: string; value: string }>;
Returns: Array<{ name: string; value: string }> - Array of form data objects
Examples:
// Get structured form data
const formArray = $('form').serializeArray();
// [{ name: 'email', value: 'user@example.com' }, { name: 'subscribe', value: 'on' }]
// Convert to object
const formObject = {};
$('form').serializeArray().forEach(item => {
formObject[item.name] = item.value;
});
Common gotchas:
- Only successful form controls are serialized
- Disabled elements are ignored
- Checkboxes/radios must be checked to be included
- File inputs return filename, not file content