### Install Cheerio
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/intro.md
Use this command to install Cheerio and its dependencies via npm.
```bash
npm install cheerio
```
--------------------------------
### Start Local Development Server
Source: https://github.com/cheeriojs/cheerio/blob/main/website/README.md
Starts a local development server for live previewing changes. The server automatically reloads the browser on most modifications.
```bash
yarn start
```
--------------------------------
### Install Cheerio using npm or bun
Source: https://github.com/cheeriojs/cheerio/blob/main/Readme.md
Install Cheerio using your preferred package manager. This is the first step before using Cheerio in your project.
```bash
npm install cheerio
# or
bun add cheerio
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/cheeriojs/cheerio/blob/main/website/README.md
Installs all necessary dependencies for the project using Yarn.
```bash
yarn
```
--------------------------------
### Install Cheerio 1.0
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/blog/2024-08-07-version-1.md
Upgrade to Cheerio 1.0 by installing the latest version using npm.
```bash
npm install cheerio@latest
```
--------------------------------
### Load HTML Document
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/intro.md
Load an HTML string into Cheerio to create a Cheerio object for DOM manipulation. This is the primary way to start working with HTML content.
```js
const $ = cheerio.load('
Hello world
');
```
--------------------------------
### Set and Get Element Attributes and Properties
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/manipulation.md
Use `attr()` to modify element attributes and `prop()` to modify element properties. Both can get and set values. When setting, they apply to all elements in the selection; when getting, they return a single value from the first element.
```javascript
// Set the 'src' attribute of an image element
$('img').attr('src', 'https://example.com/image.jpg');
// Set the 'checked' property of a checkbox element
$('input[type="checkbox"]').prop('checked', true);
// Get the 'href' attribute of a link element
const href = $('a').attr('href');
// Get the 'disabled' property of a button element
const isDisabled = $('button').prop('disabled');
```
```javascript
// Get the `style` object of an element
const style = $('div').prop('style');
// Get the resolved `src` URL of an image element
$('img').prop('src');
// Get the outerHTML of an element
const outerHTML = $('div').prop('outerHTML');
// Get the innerText of an element
const innerText = $('div').prop('innerText');
```
--------------------------------
### Select First and Last Elements in a Selection
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/traversing.mdx
Use `first` to get the first element and `last` to get the last element in a Cheerio selection. These are useful for targeting the beginning or end of a list of elements.
```javascript
const $ = cheerio.load(
`
\n
Item 1
\n
Item 2
\n
`,
);
const firstItem = $("li").first();
const lastItem = $("li").last();
console.log(`First: ${firstItem.text()}`);
console.log(`Last: ${lastItem.text()}`);
```
--------------------------------
### Extract Release Data from GitHub
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/blog/2024-08-07-version-1.md
Use the `extract` method to fetch and parse data from a URL, specifying selectors for nested values. This example extracts release name, date, and notes from a GitHub releases page.
```typescript
import * as cheerio from 'cheerio';
const $ = await cheerio.fromURL(
'https://github.com/cheeriojs/cheerio/releases',
);
const data = $.extract({
releases: [
{
// First, we select individual release sections.
selector: 'section',
// Then, we extract the release date, name, and notes from each section.
value: {
// Selectors are executed within the context of the selected element.
name: 'h2',
date: {
selector: 'relative-time',
// The actual release date is stored in the `datetime` attribute.
value: 'datetime',
},
notes: {
selector: '.markdown-body',
// We are looking for the HTML content of the element.
value: 'innerHTML',
},
},
},
],
});
```
--------------------------------
### Select Element and Get Text
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/intro.md
Select an HTML element using a CSS selector and retrieve its text content. This is a fundamental operation for web scraping.
```js
$('h2.title').text(); // "Hello world"
```
--------------------------------
### Configure HTML Parsing with parse5 Options
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/configuring-cheerio.md
Pass an extra object to `.load()` to modify parsing options for HTML input when using the default parse5 parser. For example, disable scripting to parse noscript tags as HTML.
```javascript
const cheerio = require('cheerio');
const $ = cheerio.load('', {
scriptingEnabled: false,
});
```
--------------------------------
### Set Page Background Color
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Sets the background color of the entire document's body to black. This is a simple example of applying CSS styles to the body element.
```javascript
$( document.body ).css( "background", "black" );
```
--------------------------------
### TypeScript Type Definition for Custom Method
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/extending-cheerio.md
When using TypeScript, declare the type for custom methods added to Cheerio's prototype to ensure type safety and enable autocompletion. This example adds the `logHtml` method signature.
```ts
declare module 'cheerio' {
interface Cheerio {
logHtml(this: Cheerio): void;
}
}
```
--------------------------------
### Extract Text Content of First Matching Element
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/extract.md
Use `extract` with a simple string selector to get the text content of the first element that matches the selector. This is useful for single, specific data points.
```javascript
// Extract the text content of the first .red element
const data = $.extract({
red: '.red',
});
```
--------------------------------
### Get All Children Including Text Nodes with `contents`
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/traversing.mdx
Use the `contents` method to select all children of an element, including text nodes and comment nodes. This is useful for inspecting the raw content of an element.
```javascript
const $ = cheerio.load(
`
Text
Paragraph
`,
);
const contents = $('div').contents();
console.log(`Contents count: ${contents.length}`);
```
--------------------------------
### Set and Get Element HTML Content
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/manipulation.md
Use the `html()` method to query or modify the HTML content of an element. When provided with an HTML string, it sets the inner HTML for all elements in the selection. Without arguments, it returns the inner HTML of the first element.
```javascript
// Set the inner HTML of an element
$('div').html('
Hello, World!
');
// Get the inner HTML of an element
const html = $('div').html();
```
--------------------------------
### Set and Get Element Text Content
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/manipulation.md
The `text()` method is used to query or modify the text content of elements. When given a string, it sets the text content for all elements. Without arguments, it returns the concatenated text content of all elements and their descendants.
```javascript
// Set the text content of an element
$('h1').text('Hello, World!');
// Get the text content of an element
const text = $('p').text();
```
--------------------------------
### Load HTML Document
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/selecting.md
Import Cheerio and load an HTML document to begin selecting elements. This is a prerequisite for all selection operations.
```js
import * as cheerio from 'cheerio';
// Load the document using any of the methods described in the "Loading Documents" section.
const $ = cheerio.load('...');
```
--------------------------------
### Build Static Website
Source: https://github.com/cheeriojs/cheerio/blob/main/website/README.md
Generates the static content for the website into the 'build' directory, ready for deployment to any static hosting service.
```bash
yarn build
```
--------------------------------
### Create Element with Attributes and Event Handlers
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a new div element with a class and a touchstart event handler, then appends it to the body.
```javascript
$( "", {
"class": "my-div",
on: {
touchstart: function( event ) {
// Do something
}
}
}).appendTo( "body" );
```
--------------------------------
### Hide Input Elements in a Form
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Hides all input elements contained within a specific form. This example assumes 'myForm' is a reference to a form element.
```javascript
$( myForm.elements ).hide();
```
--------------------------------
### Render Full HTML with Cheerio
Source: https://github.com/cheeriojs/cheerio/blob/main/Readme.md
Render the entire modified HTML document using the `html()` method on the root selection.
```javascript
$.root().html();
//=>
//
//
//
//
Apple
//
Orange
//
Pear
//
//
//
```
--------------------------------
### Load HTML Document with Cheerio
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/extract.md
Before using the `extract` method, import Cheerio and load an HTML document. This sets up the Cheerio object for subsequent operations.
```javascript
import * as cheerio from 'cheerio';
const $ = cheerio.load(`
One
Two
Three
Four
`);
```
--------------------------------
### Select Next and Previous Siblings with `next` and `prev`
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/traversing.mdx
Use `next` to select the immediate next sibling and `prev` for the immediate previous sibling. These methods work for each element in the selection.
```javascript
const $ = cheerio.load(
`
Item 1
Item 2
`,
);
const nextItem = $('li:first').next();
const prevItem = $('li:eq(1)').prev();
console.log(`Next: ${nextItem.text()}`);
console.log(`Prev: ${prevItem.text()}`);
```
--------------------------------
### Apply Border to Div Children Paragraphs
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Selects all paragraph elements that are direct children of a div element and applies a gray border to them. This example demonstrates descendant selector usage.
```html
jQuery demo
one
two
three
```
--------------------------------
### Create a Simple Anchor Element
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a new anchor element.
```javascript
$( "" )
```
--------------------------------
### Import Cheerio with CommonJS
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/intro.md
Import Cheerio using the require function for older environments or when using CommonJS modules.
```js
const cheerio = require('cheerio');
```
--------------------------------
### Load HTML with Cheerio
Source: https://github.com/cheeriojs/cheerio/blob/main/Readme.md
Import Cheerio and load an HTML string to create a Cheerio object for manipulation. Supports both ESM/TypeScript and CommonJS environments.
```javascript
// ESM or TypeScript:
import * as cheerio from 'cheerio';
// In other environments:
const cheerio = require('cheerio');
const $ = cheerio.load('
...
');
$.html();
//=>
...
```
--------------------------------
### Inserting Elements with prependTo() and appendTo()
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/manipulation.md
Use these methods to prepend or append an element to a parent. They accept a string or a Cheerio object.
```javascript
const $ = require('cheerio');
// Prepend an element to a parent element
$('
Inserted element
').prependTo('div');
```
```javascript
// Append an element to a parent element
$('
Inserted element
').appendTo('div');
```
--------------------------------
### Create an Input Element
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a new input element.
```javascript
$( "" );
```
--------------------------------
### Inserting Elements with insertAfter() and insertBefore()
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/manipulation.md
These methods insert a new element before or after a target element. They accept a string or a Cheerio object.
```javascript
const $ = require('cheerio');
// Insert an element after a target element
$('
Inserted element
').insertAfter('h1');
```
```javascript
// Insert an element before a target element
$('
Inserted element
').insertBefore('h1');
```
--------------------------------
### Select All Siblings with `nextAll`, `prevAll`, and `siblings`
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/traversing.mdx
Use `nextAll` to select all subsequent siblings, `prevAll` for all preceding siblings, and `siblings` for all siblings (both before and after).
```javascript
const $ = cheerio.load(
`
[1]
[2]
[3]
`,
);
const nextAll = $('li:first').nextAll();
const prevAll = $('li:last').prevAll();
const siblings = $('li:eq(1)').siblings();
console.log(`Next All: ${nextAll.text()}`);
console.log(`Prev All: ${prevAll.text()}`);
console.log(`Siblings: ${siblings.text()}`);
```
--------------------------------
### Inserting Elements with append(), prepend(), before(), after()
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/manipulation.md
Use these methods to insert new elements relative to existing ones. They modify every element in the selection.
```javascript
// Append an element to the end of a parent element
$('ul').append('
Item
');
```
```javascript
// Prepend an element to the beginning of a parent element
$('ul').prepend('
Item
');
```
```javascript
// Insert an element before a target element
$('li').before('
Item
');
```
```javascript
// Insert an element after a target element
$('li').after('
Item
');
```
--------------------------------
### Create DOM Elements with Attributes and Click Handler
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Demonstrates creating a new div element with specified class, text, and a click event handler. The element is then appended to the body.
```javascript
$( "", {
"class": "test",
text: "Click me!",
click: function() {
$( this ).toggleClass( "test" );
}
})
.appendTo( "body" );
```
--------------------------------
### Select Siblings Until a Point with `nextUntil` and `prevUntil`
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/traversing.mdx
Use `nextUntil` to select siblings after the current element up to, but not including, a specified element. `prevUntil` works similarly for preceding siblings.
```javascript
const $ = cheerio.load(
`
Item 1
Item 2
Item 3
`,
);
const nextUntil = $('li:first').nextUntil('li:last-child');
const prevUntil = $('li:last').prevUntil('li:first-child');
console.log(`Next: ${nextUntil.text()}`);
console.log(`Prev: ${prevUntil.text()}`);
```
--------------------------------
### Select the First Element
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/selecting.md
Use the ':first' pseudo-class to select the first element that matches the selector.
```js
const $p = $('p:first');
```
--------------------------------
### Load HTML from a URL
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/loading.md
The `fromURL` method asynchronously fetches and parses HTML content directly from a given URL. Use `await` or a `.then()` block to access the resulting Cheerio object.
```javascript
import * as cheerio from 'cheerio';
const $ = await cheerio.fromURL('https://example.com');
```
--------------------------------
### jQuery( callback )
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Executes a function when the DOM is ready.
```APIDOC
## jQuery( callback )
### Description
Shorthand for `$( document ).ready( handler )`, this executes a function when the DOM is fully loaded and ready for manipulation. It's a common way to ensure your code runs after the HTML structure is available.
### Method
`jQuery` or `$`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Parameters
* **callback** (Function) - Required - The function to execute when the DOM is ready.
### Request Example
```javascript
$( function() {
// DOM is ready, safe to manipulate elements
console.log( "DOM is ready!" );
});
```
### Response
#### Success Response (200)
This function does not return a value directly; it schedules the execution of the provided callback function.
```
--------------------------------
### Import Cheerio Slim Export
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/configuring-cheerio.md
Use Cheerio's slim export for browser environments to avoid loading parse5 and save bytes. This export always uses htmlparser2.
```javascript
import * as cheerio from 'cheerio/slim';
```
--------------------------------
### Import Cheerio with ES Modules
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/intro.md
Import Cheerio into your JavaScript code using the import statement for ES module environments.
```js
import * as cheerio from 'cheerio';
```
--------------------------------
### Extract Release Data from GitHub
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/extract.md
Fetches the latest Cheerio release page and extracts the release name, date, and notes using the `extract` method. Selectors are executed within the context of individual release sections.
```javascript
import * as cheerio from 'cheerio';
const $ = await cheerio.fromURL(
'https://github.com/cheeriojs/cheerio/releases',
);
const data = $.extract({
releases: [
{
// First, we select individual release sections.
selector: 'section',
// Then, we extract the release date, name, and notes from each section.
value: {
// Selectors are executed within the context of the selected element.
name: 'h2',
date: {
selector: 'relative-time',
// The actual release date is stored in the `datetime` attribute.
value: 'datetime',
},
notes: {
selector: '.markdown-body',
// We are looking for the HTML content of the element.
value: 'innerHTML',
},
},
},
],
});
```
--------------------------------
### Write Custom Cheerio Plugin Method
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/extending-cheerio.md
Extend Cheerio's functionality by adding custom methods to its prototype, such as `logHtml` which logs the HTML content of selected elements. This allows for reusable custom operations.
```js
const $ = cheerio.load('Hello, world!');
$.prototype.logHtml = function () {
console.log(this.html());
};
$('body').logHtml(); // logs "Hello, world!" to the console
```
--------------------------------
### Cheerio 1.0 Upgrade: htmlparser2 Options
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/blog/2024-08-07-version-1.md
htmlparser2 options are now exclusively located under the `xml` key when loading documents in Cheerio 1.0.
```typescript
const $ = cheerio.load('', {
xml: {
withStartIndices: true,
},
});
```
--------------------------------
### Create a Simple Image Element
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a new image element using the native JavaScript createElement() function.
```javascript
$( "" )
```
--------------------------------
### jQuery()
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates an empty jQuery object.
```APIDOC
## jQuery()
### Description
Creates an empty jQuery object. This object contains no elements and has a `.length` property of 0. It can be used as a starting point for chaining methods or as a placeholder.
### Method
`jQuery` or `$`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Parameters
None
### Request Example
```javascript
var emptySet = $( ); // Creates an empty jQuery object
console.log( emptySet.length ); // Output: 0
```
### Response
#### Success Response (200)
* **jQuery object** - An empty jQuery object.
```
--------------------------------
### Load HTML from a String
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/loading.md
Use the `load` method for parsing HTML or XML strings. It returns a Cheerio object for DOM traversal. By default, it adds ``, ``, and `` if absent; pass `false` as the third argument to disable this.
```javascript
import * as cheerio from 'cheerio';
const $ = cheerio.load('
'
```
--------------------------------
### Working with Plain Objects in jQuery
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Demonstrates how to use .data(), .prop(), .on(), .trigger(), and .triggerHandler() with plain JavaScript objects wrapped in jQuery. Note that .trigger() may execute properties on the object if they are not functions.
```javascript
// Define a plain object
var foo = { foo: "bar", hello: "world" };
// Pass it to the jQuery function
var $foo = $( foo );
// Test accessing property values
var test1 = $foo.prop( "foo" ); // bar
// Test setting property values
$foo.prop( "foo", "foobar" );
var test2 = $foo.prop( "foo" ); // foobar
// Test using .data() as summarized above
$foo.data( "keyName", "someValue" );
console.log( $foo ); // will now contain a jQuery{randomNumber} property
// Test binding an event name and triggering
$foo.on( "eventName", function () {
console.log( "eventName was called" );
});
$foo.trigger( "eventName" ); // Logs "eventName was called"
```
```javascript
$foo.triggerHandler( "eventName" ); // Also logs "eventName was called"
```
--------------------------------
### Handling Text Nodes in Element Creation
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Demonstrates how jQuery handles text nodes when creating elements, showing that they are often ignored or removed.
```javascript
var el = $( "1 2 3" ); // returns [ , "2", ]
```
```javascript
el = $( "1 2 3 >" ); // returns [ , "2", , "3 >"]
```
--------------------------------
### Load and Manipulate HTML
Source: https://github.com/cheeriojs/cheerio/blob/main/Readme.md
Load an HTML string and use Cheerio's jQuery-like API to select elements, modify their text, add classes, and render the resulting HTML. This is useful for server-side HTML processing.
```javascript
import * as cheerio from 'cheerio';
const $ = cheerio.load('
```
--------------------------------
### Select Elements with Cheerio
Source: https://github.com/cheeriojs/cheerio/blob/main/Readme.md
Use jQuery-style selectors to find and extract information from loaded HTML. Selectors can target elements by class, attribute, or hierarchy.
```javascript
'.apple', '#fruits').text();
//=> Apple
$('ul .pear').attr('class');
//=> pear
$('li[class=orange]').html();
//=> Orange
```
--------------------------------
### Create a Self-Closing Image Tag
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a new image element using a quick-close syntax.
```javascript
$( "" );
```
--------------------------------
### Wrapping Elements with wrap()
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/manipulation.md
Wrap an element with another element using the wrap() method. It accepts a string or a Cheerio object.
```javascript
// Wrap an element in a div
$('p').wrap('');
```
--------------------------------
### jQuery( html [, ownerDocument ] )
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a jQuery object from an HTML string, optionally specifying the owner document.
```APIDOC
## jQuery( html [, ownerDocument ] )
### Description
Accepts a string containing HTML markup which is then used to create DOM elements. An optional `ownerDocument` can be provided to specify the document context for creating the elements.
### Method
`jQuery` or `$`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Parameters
* **html** (String) - Required - A string of HTML markup.
* **ownerDocument** (Document) - Optional - The document in which to create the elements.
### Request Example
```javascript
var newDiv = $( "
Hello
" );
var newSpan = $( "World", document.implementation.createHTMLDocument().documentElement );
```
### Response
#### Success Response (200)
* **jQuery object** - A jQuery object containing the newly created DOM elements.
```
--------------------------------
### Select Elements by Tag and Class
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/selecting.md
Combine tag name and class selectors to find elements that match both criteria.
```js
const $selected = $('p.selected');
```
--------------------------------
### jQuery( selector [, context ] )
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Accepts a string containing a CSS selector and optionally a context to search within, returning a new jQuery object that references the matched elements.
```APIDOC
## jQuery( selector [, context ] )
### Description
Accepts a string containing a CSS selector which is then used to match a set of elements. An optional context can be provided to restrict the search.
### Method
`jQuery` or `$`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Parameters
* **selector** (Selector) - Required - A string containing a selector expression.
* **context** (Element or jQuery) - Optional - A DOM Element, Document, or jQuery object to use as context for the search.
### Request Example
```javascript
$( "div.foo" );
$( "span", this ); // Searches within 'this' context
```
### Response
#### Success Response (200)
* **jQuery object** - A jQuery object containing the matched elements. If no elements match, the object will be empty.
```
--------------------------------
### Cheerio 1.0 Upgrade: Load Documents
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/blog/2024-08-07-version-1.md
In Cheerio 1.0, always load documents first before using methods like `html()`. The deprecated static `html` function is removed.
```typescript
import * as cheerio from 'cheerio';
cheerio.load('').html();
```
--------------------------------
### Load Cheerio with htmlparser2 DOM
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/configuring-cheerio.md
Pass a pre-parsed htmlparser2 DOM structure to Cheerio's `.load()` method. Note that this method uses parse5's serializer for output.
```javascript
import * as htmlparser2 from 'htmlparser2';
const dom = htmlparser2.parseDocument(document, options);
const $ = cheerio.load(dom);
```
--------------------------------
### Configure XML Parsing with htmlparser2
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/configuring-cheerio.md
Parse XML documents by passing the `xml: true` option to `.load()`. Customize htmlparser2 options by passing an object to the `xml` option.
```javascript
const $ = cheerio.load('
', {
xml: {
withStartIndices: true,
},
});
```
--------------------------------
### Execute Function When DOM is Ready
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Use this snippet to ensure your code runs only after the DOM is fully loaded and ready for manipulation. It's equivalent to $(document).ready().
```javascript
$(function() {
// Document is ready
});
```
--------------------------------
### Select Parent Element with `parent`
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/traversing.mdx
Use the `parent` method to select the immediate parent element of the current selection. This is useful for moving up one level in the DOM tree.
```javascript
const $ = cheerio.load(
`
Item 1
`,
);
const list = $('li').parent();
console.log(list.prop('tagName'));
```
--------------------------------
### Add, Remove, and Toggle Element Classes
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/manipulation.md
Use `addClass()`, `removeClass()`, and `toggleClass()` to manage element classes. These methods accept a single class name or a space-separated list and apply to all elements in the selection.
```javascript
// Add a class to an element
$('div').addClass('new-class');
// Add multiple classes to an element
$('div').addClass('new-class another-class');
// Remove a class from an element
$('div').removeClass('old-class');
// Remove multiple classes from an element
$('div').removeClass('old-class another-class');
// Toggle a class on an element (add if it doesn't exist, remove if it does)
$('div').toggleClass('active');
```
--------------------------------
### Incident Response Checklist
Source: https://github.com/cheeriojs/cheerio/blob/main/INCIDENT_RESPONSE.md
A checklist to ensure all steps of the incident response process are followed.
```markdown
[ ] Report received and acknowledged
[ ] Severity assigned
[ ] Versions & components identified
[ ] Root cause confirmed
[ ] Fix developed with regression test
[ ] Fix reviewed by second maintainer
[ ] Patched version published to npm
[ ] GitHub Security Advisory published
[ ] Reporter credited
[ ] Post-incident review completed
[ ] This plan / threat model updated if needed
```
--------------------------------
### Create and Append a New Paragraph
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a new paragraph element with an ID and some emphasized text, then appends it to the document's body.
```javascript
$( "
My new text
" ).appendTo( "body" );
```
--------------------------------
### Select All Paragraph Elements
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/selecting.md
Use a tag name selector to retrieve all instances of a specific HTML tag.
```js
const $p = $('p');
```
--------------------------------
### jQuery( html [, ownerDocument ] )
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates DOM elements from a string of raw HTML. This method parses HTML, not XML. An optional ownerDocument can be provided to specify the document in which the new elements will be created.
```APIDOC
## jQuery( html [, ownerDocument ] )
### Description
Creates DOM elements on the fly from the provided string of raw HTML. This parses HTML, not XML. An optional ownerDocument can be provided to specify the document in which the new elements will be created.
### Method
`jQuery` (constructor)
### Parameters
#### Path Parameters
- **html** (htmlString) - Required - A string of HTML to create on the fly.
- **ownerDocument** (document) - Optional - A document in which the new elements will be created.
### Version Added
1.0
```
--------------------------------
### Select Element by Index with `eq`
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/traversing.mdx
Use `eq` to select an element at a specific zero-based index within a selection. This is useful for targeting individual elements in a list.
```javascript
const $ = cheerio.load(
`
Item 1
Item 2
`,
);
const secondItem = $('li').eq(1);
console.log(secondItem.text());
```
--------------------------------
### Select Ancestor Elements with `parents` and `parentsUntil`
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/traversing.mdx
Use `parents` to select all ancestor elements up to the root, or `parentsUntil` to stop at a specified ancestor. These methods help navigate upwards through the DOM hierarchy.
```javascript
const $ = cheerio.load(
`
Item 1
`,
);
const ancestors = $('li').parents();
const ancestorsUntil = $('li').parentsUntil('div');
console.log(`Ancestor count (includes body and html): ${ancestors.length}`);
console.log(`Ancestor count (until div): ${ancestorsUntil.length}`);
```
--------------------------------
### Create Element with Chained Methods
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a new div element and applies class and event handlers using chained jQuery methods before appending to the body.
```javascript
$( "" )
.addClass( "my-div" )
.on({
touchstart: function( event ) {
// Do something
}
})
.appendTo( "body" );
```
--------------------------------
### Load HTML from a Buffer
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/loading.md
The `loadBuffer` method parses HTML from a buffer, automatically detecting the encoding. This is ideal for data read from files or network connections.
```javascript
import * as cheerio from 'cheerio';
import * as fs from 'fs';
const buffer = fs.readFileSync('document.html');
const $ = cheerio.loadBuffer(buffer);
console.log($('title').text());
// Output: Hello, world!
```
--------------------------------
### jQuery( html, attributes )
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a single, standalone HTML element from a string and applies specified attributes, events, or methods to it.
```APIDOC
## jQuery( html, attributes )
### Description
Creates a single, standalone HTML element from a string and applies specified attributes, events, or methods to it.
### Method
`jQuery` (constructor)
### Parameters
#### Path Parameters
- **html** (htmlString) - Required - A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).
- **attributes** (PlainObject) - Required - An object of attributes, events, and methods to call on the newly-created element.
### Version Added
1.4
```
--------------------------------
### Cheerio Fragment Mode Parsing
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/configuring-cheerio.md
Use parse5's fragment mode by passing `false` as the second argument to `.load()` to parse HTML fragments as standalone documents instead of full HTML documents.
```javascript
const $ = cheerio.load('
Apple
Banana
');
$.html(); // => '
Apple
Banana
'
```
```javascript
// Note that we are passing `false`, as we are not parsing a full document.
const $ = cheerio.load('
Apple
Banana
', {}, false);
$.html(); // => '
Apple
Banana
'
```
--------------------------------
### jQuery( html, attributes )
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a jQuery object from an HTML string and an object of attributes to apply.
```APIDOC
## jQuery( html, attributes )
### Description
Accepts a string containing HTML markup and an object containing attributes to be applied to the newly created elements.
### Method
`jQuery` or `$`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Parameters
* **html** (String) - Required - A string of HTML markup.
* **attributes** (Object) - Required - An object containing key-value pairs for attributes to set on the new elements.
### Request Example
```javascript
var newButton = $( "", { "class": "btn", "id": "myBtn" } );
```
### Response
#### Success Response (200)
* **jQuery object** - A jQuery object containing the newly created DOM elements with the specified attributes.
```
--------------------------------
### jQuery()
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
The jQuery() function (often written as $()) is the entry point to the jQuery library. It can be used to select elements from the DOM or to create new HTML elements.
```APIDOC
## jQuery()
### Description
Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.
### Method
Not applicable (constructor function)
### Endpoint
Not applicable (JavaScript function)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
// Selecting existing elements
$(".my-class");
// Creating new elements
$("
Hello
");
```
### Response
#### Success Response
A jQuery object containing the matched or created elements.
#### Response Example
```javascript
// Example of a jQuery object (representation varies)
{
"0": HTMLElement,
"length": 1,
"prevObject": { ... },
"context": document,
"selector": ".my-class"
}
```
```
--------------------------------
### Select Elements by Class Name
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/selecting.md
Use a class selector (prefixed with '.') to find all elements with a specific class.
```js
const $selected = $('.selected');
```
--------------------------------
### jQuery()
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Calling the jQuery() method with no arguments returns an empty jQuery set with a length property of 0.
```APIDOC
## jQuery()
### Description
Calling the jQuery() method with no arguments returns an empty jQuery set (with a [.length](/length/) property of 0).
### Method
`jQuery` (constructor)
### Version Added
1.4
```
--------------------------------
### Working With Plain Objects
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Operations supported on plain JavaScript objects wrapped in jQuery include .data(), .prop(), .on(), .off(), .trigger(), and .triggerHandler(). Using .data() on a plain object adds a jQuery{randomNumber} property.
```APIDOC
## Working With Plain Objects
### Description
At present, the only operations supported on plain JavaScript objects wrapped in jQuery are: `.data()`, `.prop()`, `.on()`, `.off()`, `.trigger()` and `.triggerHandler()`. The use of `.data()` (or any method requiring `.data()`) on a plain object will result in a new property on the object called jQuery{randomNumber} (eg. jQuery123456789).
### Supported Methods
- `.data( key, value )`
- `.prop( name [, value ] )`
- `.on( events [, selector ] [, data ], handler )
- `.off( events [, selector ] [, handler ] )
- `.trigger( type [, eventData ] )
- `.triggerHandler( type [, eventData ] )`
### Example
```javascript
// Define a plain object
var foo = { foo: "bar", hello: "world" };
// Pass it to the jQuery function
var $foo = $( foo );
// Test accessing property values
var test1 = $foo.prop( "foo" ); // bar
// Test setting property values
$foo.prop( "foo", "foobar" );
var test2 = $foo.prop( "foo" ); // foobar
// Test using .data() as summarized above
$foo.data( "keyName", "someValue" );
console.log( $foo ); // will now contain a jQuery{randomNumber} property
// Test binding an event name and triggering
$foo.on( "eventName", function () {
console.log( "eventName was called" );
});
$foo.trigger( "eventName" ); // Logs "eventName was called"
// To avoid .trigger() searching for properties, use .triggerHandler()
$foo.triggerHandler( "eventName" ); // Also logs "eventName was called"
```
```
--------------------------------
### jQuery( jQuery object )
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a clone of an existing jQuery object.
```APIDOC
## jQuery( jQuery object )
### Description
Creates a clone of an existing jQuery object. This results in a new jQuery object that contains the same set of elements as the original, but is a distinct object.
### Method
`jQuery` or `$`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Parameters
* **jQuery object** (jQuery) - Required - An existing jQuery object to clone.
### Request Example
```javascript
var originalSet = $( "div.foo" );
var clonedSet = $( originalSet ); // clonedSet is a new jQuery object with the same elements
```
### Response
#### Success Response (200)
* **jQuery object** - A new jQuery object that is a clone of the input jQuery object.
```
--------------------------------
### Render Text Content with Cheerio
Source: https://github.com/cheeriojs/cheerio/blob/main/Readme.md
Extract only the text content from a Cheerio selection, stripping out any HTML tags, using the `text()` method.
```javascript
const $ = cheerio.load('This is content.');
$('body').text();
//=> This is content.
```
--------------------------------
### Create a Well-Formed Anchor Tag
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a new anchor element with an href attribute, ensuring proper tag pairing for compatibility.
```javascript
$( "" );
```
--------------------------------
### Extract Data Using a Custom Function
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/extract.md
For complex transformations, provide a function as the `value`. This function receives the element and key, allowing custom logic for data extraction and formatting.
```javascript
const data = $.extract({
links: [
{
selector: 'a',
value: (el, key) => {
const href = $(el).attr('href');
return `${key}=${href}`;
},
},
],
});
```
--------------------------------
### Load HTML from a String Stream
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/loading.md
Use `stringStream` to parse an HTML document from a stream when the encoding is known. It pipes the stream into Cheerio for processing.
```javascript
import * as cheerio from 'cheerio';
import * as fs from 'fs';
const writeStream = cheerio.stringStream({}, (err, $) => {
if (err) {
// Handle error
}
console.log($('title').text());
// Output: Hello, world!
});
fs.createReadStream('document.html', { encoding: 'utf8' }).pipe(writeStream);
```
--------------------------------
### Create Element for a Specific Document
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates a new paragraph element intended for insertion into a document associated with an iframe.
```javascript
$("
hello iframe
", $("#myiframe").prop("contentWindow").document)
```
--------------------------------
### Create DOM Elements from HTML String
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Creates DOM elements from a provided string of raw HTML. This method parses HTML, not XML, and can optionally take an owner document.
```javascript
jQuery( htmlString );
```
--------------------------------
### Add Custom CSS Pseudo-Classes
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/extending-cheerio.md
Define custom pseudo-classes like `:foo` (selector-based) and `:bar(val)` (function-based) to enhance element selection. The function-based pseudo-class receives the element and any provided arguments.
```js
const $ = cheerio.load('', {
pseudos: {
// `:foo` is an alias for `div.foo`
foo: 'div.foo',
// `:bar(val)` is equivalent to `[data-bar=val s]`
bar: (el, val) => el.attribs['data-bar'] === val,
},
});
$(':foo').length; // 1
$('div:bar(boo)').length; // 1
$('div:bar(baz)').length; // 0
```
--------------------------------
### Create a jQuery object from a plain object
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
This creates a jQuery object from a plain JavaScript object.
```javascript
var plainObject = { key: "value" };
$( plainObject );
```
--------------------------------
### jQuery( element )
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Wraps a single DOM element in a jQuery object.
```APIDOC
## jQuery( element )
### Description
Wraps a single DOM element in a jQuery object. This is useful when you have a bare DOM element (e.g., from an event handler) and want to apply jQuery methods to it.
### Method
`jQuery` or `$`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Parameters
* **element** (Element) - Required - A DOM element to wrap in a jQuery object.
### Request Example
```javascript
$( "div.foo" ).click(function() {
$( this ).slideUp(); // Apply jQuery method to the clicked element
});
```
### Response
#### Success Response (200)
* **jQuery object** - A jQuery object wrapping the provided DOM element.
```
--------------------------------
### Select elements using a CSS selector
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Use this to select DOM elements based on CSS selectors. The search is performed within the document root by default.
```javascript
$( "div.foo" );
```
--------------------------------
### Create a jQuery object from an existing jQuery object
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
This creates a clone of an existing jQuery object.
```javascript
var existingJqueryObject = $( "#someId" );
var clonedJqueryObject = $( existingJqueryObject );
```
--------------------------------
### Select Descendant Elements
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/selecting.md
Use a space in the selector to find elements that are descendants of another element.
```js
const $p = $('div p');
```
--------------------------------
### Find and Select Nested Elements
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/intro.md
Use the `find` function to select elements that are descendants of already selected elements. This allows for more specific DOM traversal.
```js
$('h2.title').find('.subtitle').text();
```
--------------------------------
### Find Descendant Elements with `find`
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/traversing.mdx
Use the `find` method to select specific descendant elements within the current selection. It takes a CSS selector as an argument.
```javascript
const $ = cheerio.load(
`
Item 1
Item 2
`,
);
const listItems = $('ul').find('li');
console.log(`List item count: ${listItems.length}`);
```
--------------------------------
### Select Radio Inputs in First Form
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Finds all input elements of type radio within the first form element present in the document. This utilizes the :radio selector and context argument.
```javascript
$( "input:radio", document.forms[ 0 ] );
```
--------------------------------
### Select Elements by Attribute Value
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/selecting.md
Use an attribute selector (e.g., '[attribute=value]') to select elements based on their attribute and value.
```js
const $selected = $('[data-selected=true]');
```
--------------------------------
### Load HTML from a Stream with Unknown Encoding
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/loading.md
When the encoding of an HTML document from a stream is unknown, `decodeStream` is used. It applies an encoding sniffing algorithm to determine the correct encoding before parsing.
```javascript
import * as cheerio from 'cheerio';
import * as fs from 'fs';
const writeStream = cheerio.decodeStream({}, (err, $) => {
if (err) {
// Handle error
}
console.log($('title').text());
// Output: Hello, world!
});
fs.createReadStream('document.html').pipe(writeStream);
```
--------------------------------
### Create and Append a Complex Div Element
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Dynamically creates a div element containing a paragraph and appends it to the body. Internally, an element is created and its innerHTML property is set to the provided markup.
```javascript
$( "
Hello
" ).appendTo( "body" )
```
--------------------------------
### Replacing Elements with replaceWith()
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/basics/manipulation.md
Replace an element with new content using replaceWith(). It accepts a string or a Cheerio object and removes the original element.
```javascript
// Replace an element with another element
$('li').replaceWith('
Item
');
```
--------------------------------
### jQuery Document Ready with Safe Alias
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Use this snippet to ensure your jQuery code runs after the DOM is fully loaded and to use a safe $ alias, preventing conflicts with other libraries.
```javascript
jQuery(function( $ ) {
// Your code using failsafe $ alias here...
});
```
--------------------------------
### Use htmlparser2 for HTML Parsing
Source: https://github.com/cheeriojs/cheerio/blob/main/website/src/content/docs/advanced/configuring-cheerio.md
Parse HTML with htmlparser2 by disabling `xmlMode` within the `xml` option. This is useful for older Cheerio versions, invalid markup, or performance-critical situations.
```javascript
const $ = cheerio.load('
...
', {
xml: {
// Disable `xmlMode` to parse HTML with htmlparser2.
xmlMode: false,
},
});
```
--------------------------------
### jQuery( elementArray )
Source: https://github.com/cheeriojs/cheerio/blob/main/benchmark/documents/jquery.html
Wraps an array of DOM elements in a jQuery object.
```APIDOC
## jQuery( elementArray )
### Description
Wraps an array of DOM elements in a jQuery object. This allows you to apply jQuery methods to a collection of elements that you have already selected.
### Method
`jQuery` or `$`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Parameters
* **elementArray** (Array) - Required - An array containing a set of DOM elements to wrap in a jQuery object.
### Request Example
```javascript
var elements = document.getElementsByTagName('p');
$( elements ).css( "color", "red" );
```
### Response
#### Success Response (200)
* **jQuery object** - A jQuery object wrapping the provided array of DOM elements.
```