Showing preview only (748K chars total). Download the full file or copy to clipboard to get everything.
Repository: cheeriojs/cheerio
Branch: main
Commit: 1e7f681c84a1
Files: 104
Total size: 713.4 KB
Directory structure:
gitextract_2mrqq2gl/
├── .gitattributes
├── .github/
│ ├── FUNDING.yml
│ ├── dependabot.yml
│ ├── issue_template.md
│ └── workflows/
│ ├── benchmark.yml
│ ├── ci.yml
│ ├── codeql.yml
│ ├── dependabot-automerge.yml
│ ├── lint.yml
│ ├── site.yml
│ └── sponsors.yml
├── .gitignore
├── .husky/
│ ├── .gitignore
│ └── pre-commit
├── CONTRIBUTING.md
├── LICENSE
├── Readme.md
├── SECURITY.md
├── benchmark/
│ ├── benchmark.ts
│ └── documents/
│ └── jquery.html
├── biome.json
├── eslint.config.js
├── package.json
├── scripts/
│ └── fetch-sponsors.mts
├── src/
│ ├── __fixtures__/
│ │ └── fixtures.ts
│ ├── __tests__/
│ │ ├── deprecated.spec.ts
│ │ └── xml.spec.ts
│ ├── api/
│ │ ├── attributes.spec.ts
│ │ ├── attributes.ts
│ │ ├── css.spec.ts
│ │ ├── css.ts
│ │ ├── extract.spec.ts
│ │ ├── extract.ts
│ │ ├── forms.spec.ts
│ │ ├── forms.ts
│ │ ├── manipulation.spec.ts
│ │ ├── manipulation.ts
│ │ ├── traversing.spec.ts
│ │ └── traversing.ts
│ ├── cheerio.spec.ts
│ ├── cheerio.ts
│ ├── index-browser.mts
│ ├── index.spec.ts
│ ├── index.ts
│ ├── load-parse.ts
│ ├── load.spec.ts
│ ├── load.ts
│ ├── options.ts
│ ├── parse.spec.ts
│ ├── parse.ts
│ ├── parsers/
│ │ └── parse5-adapter.ts
│ ├── slim.ts
│ ├── static.spec.ts
│ ├── static.ts
│ ├── types.ts
│ ├── utils.spec.ts
│ └── utils.ts
├── tsconfig.json
├── tsconfig.typedoc.json
├── vitest.config.ts
└── website/
├── README.md
├── astro.config.mjs
├── package.json
├── sponsors.json
├── src/
│ ├── components/
│ │ ├── Features.astro
│ │ ├── Footer.astro
│ │ ├── Hero.astro
│ │ ├── LiveEditor.astro
│ │ ├── Navbar.astro
│ │ ├── Sidebar.astro
│ │ ├── Sponsors.astro
│ │ ├── TableOfContents.astro
│ │ ├── Testimonials.astro
│ │ └── live-code.tsx
│ ├── content/
│ │ ├── blog/
│ │ │ ├── 2023-02-13-new-website.md
│ │ │ └── 2024-08-07-version-1.md
│ │ ├── config.ts
│ │ └── docs/
│ │ ├── advanced/
│ │ │ ├── configuring-cheerio.md
│ │ │ ├── extending-cheerio.md
│ │ │ └── extract.md
│ │ ├── basics/
│ │ │ ├── loading.md
│ │ │ ├── manipulation.md
│ │ │ ├── selecting.md
│ │ │ └── traversing.mdx
│ │ └── intro.md
│ ├── env.d.ts
│ ├── layouts/
│ │ ├── BaseLayout.astro
│ │ ├── BlogLayout.astro
│ │ └── DocsLayout.astro
│ ├── pages/
│ │ ├── blog/
│ │ │ ├── [slug].astro
│ │ │ ├── index.astro
│ │ │ └── rss.xml.ts
│ │ ├── docs/
│ │ │ ├── [slug].astro
│ │ │ ├── advanced/
│ │ │ │ └── [slug].astro
│ │ │ ├── api/
│ │ │ │ └── [...slug].astro
│ │ │ └── basics/
│ │ │ └── [slug].astro
│ │ └── index.astro
│ ├── plugins/
│ │ ├── rehype-external-links.ts
│ │ ├── remark-admonitions.ts
│ │ ├── remark-fix-typedoc-links.ts
│ │ └── remark-live-code.ts
│ └── styles/
│ └── global.css
├── tsconfig.json
└── typedoc.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
# Enforce Unix newlines
* text=auto eol=lf
benchmark/documents/* binary
benchmark/jquery*.js binary
================================================
FILE: .github/FUNDING.yml
================================================
github: [cheeriojs, fb55]
open_collective: cheerio
================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: npm
directory: '/'
schedule:
interval: daily
open-pull-requests-limit: 10
versioning-strategy: increase
- package-ecosystem: npm
directory: '/website'
schedule:
interval: daily
open-pull-requests-limit: 4
versioning-strategy: increase
- package-ecosystem: 'github-actions'
directory: '/'
schedule:
interval: daily
================================================
FILE: .github/issue_template.md
================================================
<!-- Thanks for your interest in cheerio!
Please note that issues should be primarily used for tracking bugs and feature requests.
If you have a more general question, please consider consulting StackOverflow first:
https://stackoverflow.com/questions/tagged/cheerio
If you think you uncovered a bug, please try to provide a minimal example that triggers the behavior.
Please note that we will not investigate issues that perform HTTP requests, as the source might already have changed.
-->
================================================
FILE: .github/workflows/benchmark.yml
================================================
name: Benchmark
on:
push:
branches-ignore:
- 'dependabot/**'
pull_request:
env:
FORCE_COLOR: 2
permissions:
contents: read
jobs:
benchmark:
runs-on: ubuntu-latest
if:
"!contains(github.event.commits[0].message, '[bench skip]') &&
!contains(github.event.commits[0].message, '[skip bench]')"
steps:
- name: Clone repository
uses: actions/checkout@v6
- name: Set up Node.js
uses: actions/setup-node@v6.3.0
with:
node-version: lts/*
cache: 'npm'
- name: Install npm dependencies
run: npm ci
- name: Run benchmarks
run: npm run benchmark
env:
BENCHMARK: true
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on:
push:
branches-ignore:
- 'dependabot/**'
pull_request:
env:
FORCE_COLOR: 2
NODE_COV: lts/* # The Node.js version to run coveralls on
permissions:
contents: read
jobs:
run:
permissions:
checks: write # for coverallsapp/github-action to create new checks
contents: read # for actions/checkout to fetch code
name: Node ${{ matrix.node }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node:
- 20
- 22
- 24
- lts/*
steps:
- name: Clone repository
uses: actions/checkout@v6
- name: Set up Node.js
uses: actions/setup-node@v6.3.0
with:
node-version: '${{ matrix.node }}'
cache: 'npm'
- name: Install npm dependencies
run: npm ci
- name: Run tests
run: npm run test:vi
if: matrix.node != env.NODE_COV
- name: Run tests with coverage
run: npm run test:vi -- --coverage
if: matrix.node == env.NODE_COV
- name: Run Coveralls
uses: coverallsapp/github-action@v2.3.7
if: matrix.node == env.NODE_COV
continue-on-error: true
with:
github-token: '${{ secrets.GITHUB_TOKEN }}'
================================================
FILE: .github/workflows/codeql.yml
================================================
name: 'CodeQL'
on:
push:
branches:
- main
- '!dependabot/**'
pull_request:
# The branches below must be a subset of the branches above
branches:
- main
- '!dependabot/**'
schedule:
- cron: '0 0 * * 0'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
languages: 'javascript'
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4
================================================
FILE: .github/workflows/dependabot-automerge.yml
================================================
# Based on https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/automating-dependabot-with-github-actions#enable-auto-merge-on-a-pull-request
name: Dependabot auto-merge
on: pull_request_target
permissions:
pull-requests: write
contents: write
jobs:
dependabot:
runs-on: ubuntu-latest
if: ${{ github.actor == 'dependabot[bot]' }}
steps:
- name: Dependabot metadata
id: metadata
uses: dependabot/fetch-metadata@v2.5.0
with:
github-token: '${{ secrets.GITHUB_TOKEN }}'
- name: Enable auto-merge for Dependabot PRs
# Automatically merge semver-patch and semver-minor PRs
if:
"${{ steps.metadata.outputs.update-type ==
'version-update:semver-minor' || steps.metadata.outputs.update-type ==
'version-update:semver-patch' }}"
run: gh pr merge --auto --squash "$PR_URL"
env:
PR_URL: ${{github.event.pull_request.html_url}}
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
================================================
FILE: .github/workflows/lint.yml
================================================
name: Lint
on:
push:
branches-ignore:
- 'dependabot/**'
pull_request:
env:
FORCE_COLOR: 2
permissions:
contents: read
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Clone repository
uses: actions/checkout@v6
- name: Set up Node.js
uses: actions/setup-node@v6.3.0
with:
node-version: lts/*
cache: 'npm'
- name: Install npm dependencies
run: npm ci
- name: Install website npm dependencies
run: npm ci
working-directory: website
- name: Build Cheerio
run: npm run build
- name: Undo changes to package.json
run: git restore package.json
- name: Build website
run: npm run build
working-directory: website
- name: Run lint
run: npm run lint
================================================
FILE: .github/workflows/site.yml
================================================
name: Deploy website to GitHub Pages
# Based on https://raw.githubusercontent.com/actions/starter-workflows
on:
# Runs on pushes targeting the main branch
push:
branches: [main]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
env:
FORCE_COLOR: 2
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow one concurrent deployment
concurrency:
group: 'pages'
cancel-in-progress: true
jobs:
# Build job
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Node
uses: actions/setup-node@v6.3.0
with:
# Use current Node LTS version
node-version: lts/*
cache: 'npm'
- name: Setup Pages
id: pages
uses: actions/configure-pages@v5
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Install website dependencies
working-directory: website
run: npm ci
- name: Build docs
working-directory: website
run: npm run build
- name: Upload artifact
uses: actions/upload-pages-artifact@v4
with:
path: ./website/dist
# Deployment job
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
if: ${{github.repository == 'cheeriojs/cheerio'}}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
================================================
FILE: .github/workflows/sponsors.yml
================================================
name: Update Sponsors
on:
schedule:
# Run once a day, at 4pm
- cron: '0 16 * * *'
# Allow manual trigger
workflow_dispatch:
env:
FORCE_COLOR: 2
permissions:
contents: read
jobs:
fetch:
permissions:
contents: write # for peter-evans/create-pull-request to create branch
pull-requests: write # for peter-evans/create-pull-request to create a PR
runs-on: ubuntu-latest
steps:
- name: Clone repository
uses: actions/checkout@v6
- name: Set up Node.js
uses: actions/setup-node@v6.3.0
with:
node-version: lts/*
cache: 'npm'
- name: Install npm dependencies
run: npm ci
- name: Update the README
run: npm run update-sponsors
env:
CHEERIO_SPONSORS_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
IMGIX_TOKEN: ${{ secrets.IMGIX_TOKEN }}
- name: Create Pull Request
uses: peter-evans/create-pull-request@v8
continue-on-error: true
with:
commit-message: 'docs(readme): Update Sponsors'
title: Update Sponsors
branch: docs/sponsors
delete-branch: true
================================================
FILE: .gitignore
================================================
node_modules
npm-debug.log
.DS_Store
.docusaurus
.cache-loader
/coverage
/.tshy
/.tshy-build
/dist
# Website build artifacts
website/.astro/
website/dist/
website/src/content/docs/api
================================================
FILE: .husky/.gitignore
================================================
_
================================================
FILE: .husky/pre-commit
================================================
lint-staged
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to Cheerio
Thanks for your interest in contributing to the project! Here's a rundown of how
we'd like to work with you:
1. File an issue on GitHub describing the contribution you'd like to make. This
will help us to get you started on the right foot.
2. Fork the project, and make your changes in a new branch based off of the
`main` branch:
1. Follow the project's code style (see below)
2. Add enough unit tests to "prove" that your patch is correct
3. Update the project documentation as needed (see below)
4. Describe your approach with as much detail as necessary in the git
commit message
3. Open a pull request, and reference the initial issue in the pull request
message.
# Documentation
Any API change should be reflected in the project's README.md file. Reuse
[jQuery's documentation](https://api.jquery.com) wherever possible, but take
care to note aspects that make Cheerio distinct.
# Code Style
Please make sure commit hooks are run, which will enforce the code style.
When implementing private functionality that isn't part of the jQuery API,
please opt for:
- _Static methods_: If the functionality does not require a reference to a
Cheerio instance, simply define a named function within the module it is
needed.
- _Instance methods_: If the functionality requires a reference to a Cheerio
instance, informally define the method as "private" using the following
conventions:
- Define the method as a function on the Cheerio prototype
- Prefix the method name with an underscore (`_`) character
- Include `@api private` in the code comment the documents the method
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2022 The Cheerio contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: Readme.md
================================================
<h1 align="center">cheerio</h1>
<h5 align="center">The fast, flexible, and elegant library for parsing and manipulating HTML and XML.</h5>
<div align="center">
<a href="https://github.com/cheeriojs/cheerio/actions/workflows/ci.yml">
<img src="https://github.com/cheeriojs/cheerio/actions/workflows/ci.yml/badge.svg" alt="Build Status">
</a>
<a href="https://coveralls.io/github/cheeriojs/cheerio">
<img src="https://img.shields.io/coveralls/github/cheeriojs/cheerio/main" alt="Coverage">
</a>
<a href="#backers">
<img src="https://img.shields.io/opencollective/backers/cheerio" alt="OpenCollective backers">
</a>
<a href="#sponsors">
<img src="https://img.shields.io/opencollective/sponsors/cheerio" alt="OpenCollective sponsors">
</a>
</div>
<br>
[中文文档 (Chinese Readme)](https://github.com/cheeriojs/cheerio/wiki/Chinese-README)
```js
import * as cheerio from 'cheerio';
const $ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
$.html();
//=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
```
## Installation
Install Cheerio using a package manager like npm, yarn, or bun.
```bash
npm install cheerio
# or
bun add cheerio
```
## Features
**❤ Proven syntax:** Cheerio implements a subset of core jQuery. Cheerio
removes all the DOM inconsistencies and browser cruft from the jQuery library,
revealing its truly gorgeous API.
**ϟ Blazingly fast:** Cheerio works with a very simple, consistent DOM
model. As a result parsing, manipulating, and rendering are incredibly
efficient.
**❁ Incredibly flexible:** Cheerio wraps around
[parse5](https://github.com/inikulin/parse5) for parsing HTML and can optionally
use the forgiving [htmlparser2](https://github.com/fb55/htmlparser2/). Cheerio
can parse nearly any HTML or XML document. Cheerio works in both browser and
server environments.
## API
### Loading
First you need to load in the HTML. This step in jQuery is implicit, since
jQuery operates on the one, baked-in DOM. With Cheerio, we need to pass in the
HTML document.
```js
// ESM or TypeScript:
import * as cheerio from 'cheerio';
// In other environments:
const cheerio = require('cheerio');
const $ = cheerio.load('<ul id="fruits">...</ul>');
$.html();
//=> <html><head></head><body><ul id="fruits">...</ul></body></html>
```
### Selectors
Once you've loaded the HTML, you can use jQuery-style selectors to find elements
within the document.
#### \$( selector, [context], [root] )
`selector` searches within the `context` scope which searches within the `root`
scope. `selector` and `context` can be a string expression, DOM Element, array
of DOM elements, or cheerio object. `root`, if provided, is typically the HTML
document string.
This selector method is the starting point for traversing and manipulating the
document. Like in jQuery, it's the primary method for selecting elements in the
document.
```js
$('.apple', '#fruits').text();
//=> Apple
$('ul .pear').attr('class');
//=> pear
$('li[class=orange]').html();
//=> Orange
```
### Rendering
When you're ready to render the document, you can call the `html` method on the
"root" selection:
```js
$.root().html();
//=> <html>
// <head></head>
// <body>
// <ul id="fruits">
// <li class="apple">Apple</li>
// <li class="orange">Orange</li>
// <li class="pear">Pear</li>
// </ul>
// </body>
// </html>
```
If you want to render the
[`outerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML)
of a selection, you can use the `outerHTML` prop:
```js
$('.pear').prop('outerHTML');
//=> <li class="pear">Pear</li>
```
You may also render the text content of a Cheerio object using the `text`
method:
```js
const $ = cheerio.load('This is <em>content</em>.');
$('body').text();
//=> This is content.
```
### The "DOM Node" object
Cheerio collections are made up of objects that bear some resemblance to
[browser-based DOM nodes](https://developer.mozilla.org/en-US/docs/Web/API/Node).
You can expect them to define the following properties:
- `tagName`
- `parentNode`
- `previousSibling`
- `nextSibling`
- `nodeValue`
- `firstChild`
- `childNodes`
- `lastChild`
## Screencasts
[https://vimeo.com/31950192](https://vimeo.com/31950192)
> This video tutorial is a follow-up to Nettut's "How to Scrape Web Pages with
> Node.js and jQuery", using cheerio instead of JSDOM + jQuery. This video shows
> how easy it is to use cheerio and how much faster cheerio is than JSDOM +
> jQuery.
## Cheerio in the real world
Are you using cheerio in production? Add it to the
[wiki](https://github.com/cheeriojs/cheerio/wiki/Cheerio-in-Production)!
## Sponsors
Does your company use Cheerio in production? Please consider
[sponsoring this project](https://github.com/cheeriojs/cheerio?sponsor=1)! Your
help will allow maintainers to dedicate more time and resources to its
development and support.
**Headlining Sponsors**
<!-- BEGIN SPONSORS: headliner -->
<a href="https://github.com/" target="_blank" rel="noopener noreferrer">
<img height="128px" width="128px" src="https://humble.imgix.net/https%3A%2F%2Fgithub.com%2Fgithub.png?ixlib=js-3.8.0&w=128&h=128&fit=fillmax&fill=solid&s=a1e87ca289de84eb32ea85432cf8ad11" title="Github" alt="Github"></img>
</a>
<a href="https://www.airbnb.com/" target="_blank" rel="noopener noreferrer">
<img height="128px" width="128px" src="https://humble.imgix.net/https%3A%2F%2Fgithub.com%2Fairbnb.png?ixlib=js-3.8.0&w=128&h=128&fit=fillmax&fill=solid&s=384cad45e10faea516202ad10801f895" title="AirBnB" alt="AirBnB"></img>
</a>
<a href="https://hasdata.com" target="_blank" rel="noopener noreferrer">
<img height="128px" width="128px" src="https://humble.imgix.net/https%3A%2F%2Fhasdata.com%2Ffavicon.svg?ixlib=js-3.8.0&w=128&h=128&fit=fillmax&fill=solid&s=21933842d61dec74a961fc57754e58cb" title="HasData" alt="HasData"></img>
</a>
<a href="https://brand.dev/" target="_blank" rel="noopener noreferrer">
<img height="128px" width="128px" src="https://humble.imgix.net/https%3A%2F%2Fgithub.com%2Fbrand-dot-dev.png?ixlib=js-3.8.0&w=128&h=128&fit=fillmax&fill=solid&s=b870a71fedf0e9b2af5534a8aaf22abb" title="brand.dev" alt="brand.dev"></img>
</a>
<!-- END SPONSORS -->
**Other Sponsors**
<!-- BEGIN SPONSORS: sponsor -->
<a href="https://onlinecasinosspelen.com" target="_blank" rel="noopener noreferrer">
<img height="64px" width="64px" src="https://humble.imgix.net/https%3A%2F%2Fimages.opencollective.com%2Fonlinecasinosspelen%2F99ac6a2%2Flogo.png?ixlib=js-3.8.0&w=64&h=64&fit=fillmax&fill=solid&s=8ec1ec058845b823858f22205485be02" title="OnlineCasinosSpelen" alt="OnlineCasinosSpelen"></img>
</a>
<a href="https://Nieuwe-Casinos.net" target="_blank" rel="noopener noreferrer">
<img height="64px" width="64px" src="https://humble.imgix.net/https%3A%2F%2Fimages.opencollective.com%2Fnieuwecasinos%2Fc67d423%2Flogo.png?ixlib=js-3.8.0&w=64&h=64&fit=fillmax&fill=solid&s=ed55d86b80b1aa8cf89b033020521945" title="Nieuwe-Casinos.net" alt="Nieuwe-Casinos.net"></img>
</a>
<!-- END SPONSORS -->
## Backers
[Become a backer](https://github.com/cheeriojs/cheerio?sponsor=1) to show your
support for Cheerio and help us maintain and improve this open source project.
<!-- BEGIN SPONSORS: backer -->
<a href="https://kafidoff.com" target="_blank" rel="noopener noreferrer">
<img height="64px" width="64px" src="https://humble.imgix.net/https%3A%2F%2Fimages.opencollective.com%2Fkafidoff-vasy%2Fd7ff85c%2Favatar.png?ixlib=js-3.8.0&w=64&h=64&fit=fillmax&fill=solid&s=a41c66c2f9b1d3a7a241e425e7aa2d09" title="Vasy Kafidoff" alt="Vasy Kafidoff"></img>
</a>
<!-- END SPONSORS -->
## License
MIT
================================================
FILE: SECURITY.md
================================================
# Security Policy
## Supported Versions
Only the latest release will receive security updates.
## Reporting a Vulnerability
To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security). Tidelift will
coordinate the fix and disclosure.
================================================
FILE: benchmark/benchmark.ts
================================================
import fs from 'node:fs/promises';
import { Script } from 'node:vm';
import type { Element } from 'domhandler';
import { JSDOM } from 'jsdom';
import { Bench } from 'tinybench';
import type { Cheerio } from '../src/cheerio.js';
import type { CheerioAPI } from '../src/load.js';
import { load } from '../src/load-parse.js';
const documentDir = new URL('documents/', import.meta.url);
const jQuerySrc = await fs.readFile(
new URL('../node_modules/jquery/dist/jquery.slim.js', import.meta.url),
'utf8',
);
const jQueryScript = new Script(jQuerySrc);
const filterIndex = process.argv.indexOf('--filter') + 1;
const benchmarkFilter = filterIndex > 0 ? process.argv[filterIndex] : '';
const cheerioOnly = process.argv.includes('--cheerio-only');
type SuiteOptions<T> = T extends void
? {
test(this: void, $: CheerioAPI): void;
setup?: (this: void, $: CheerioAPI) => T;
}
: {
test(this: void, $: CheerioAPI, data: T): void;
setup(this: void, $: CheerioAPI): T;
};
async function benchmark<T = void>(
name: string,
fileName: string,
options: SuiteOptions<T>,
): Promise<void> {
if (!name.includes(benchmarkFilter)) {
return;
}
const markup = await fs.readFile(new URL(fileName, documentDir), 'utf8');
console.log(`Test: ${name} (file: ${fileName})`);
const bench = new Bench();
const { test, setup } = options;
// Add Cheerio test
const $ = load(markup);
const setupData = setup?.($) as T;
bench.add('cheerio', () => {
test($, setupData);
});
// Add JSDOM test
if (!cheerioOnly) {
const dom = new JSDOM(markup, { runScripts: 'outside-only' });
jQueryScript.runInContext(dom.getInternalVMContext());
const setupData = setup?.(dom.window['$'] as CheerioAPI) as T;
bench.add('jsdom', () => test(dom.window['$'] as CheerioAPI, setupData));
}
await bench.run();
console.table(bench.table());
}
await benchmark('Select all', 'jquery.html', {
test: ($) => $('*').length,
});
await benchmark('Select some', 'jquery.html', {
test: ($) => $('li').length,
});
/*
* Manipulation Tests
*/
const DIVS_MARKUP = '<div>'.repeat(50);
await benchmark<Cheerio<Element>>('manipulation - append', 'jquery.html', {
setup: ($) => $('body'),
test: (_, $body) => $body.append(DIVS_MARKUP),
});
// JSDOM used to run out of memory on these tests
await benchmark<Cheerio<Element>>(
'manipulation - prepend - highmem',
'jquery.html',
{
setup: ($) => $('body'),
test: (_, $body) => $body.prepend(DIVS_MARKUP),
},
);
await benchmark<Cheerio<Element>>(
'manipulation - after - highmem',
'jquery.html',
{
setup: ($) => $('body'),
test: (_, $body) => $body.after(DIVS_MARKUP),
},
);
await benchmark<Cheerio<Element>>(
'manipulation - before - highmem',
'jquery.html',
{
setup: ($) => $('body'),
test: (_, $body) => $body.before(DIVS_MARKUP),
},
);
await benchmark<Cheerio<Element>>('manipulation - remove', 'jquery.html', {
setup: ($) => $('body'),
test($, $lis) {
const child = $('<div>');
$lis.append(child);
child.remove();
},
});
await benchmark('manipulation - replaceWith', 'jquery.html', {
setup($) {
$('body').append('<div id="foo">');
},
test($) {
$('#foo').replaceWith('<div id="foo">');
},
});
await benchmark<Cheerio<Element>>('manipulation - empty', 'jquery.html', {
setup: ($) => $('li'),
test(_, $lis) {
$lis.empty();
},
});
await benchmark<Cheerio<Element>>('manipulation - html', 'jquery.html', {
setup: ($) => $('li'),
test(_, $lis) {
$lis.html();
$lis.html('foo');
},
});
await benchmark<Cheerio<Element>>('manipulation - html render', 'jquery.html', {
setup: ($) => $('body'),
test(_, $lis) {
$lis.html();
},
});
const HTML_INDEPENDENT_MARKUP =
'<div class="foo"><div id="bar">bat<hr>baz</div> </div>'.repeat(6);
await benchmark('manipulation - html independent', 'jquery.html', {
test: ($) => $(HTML_INDEPENDENT_MARKUP).html(),
});
await benchmark<Cheerio<Element>>('manipulation - text', 'jquery.html', {
setup: ($) => $('li'),
test(_, $lis) {
$lis.text();
$lis.text('foo');
},
});
/*
* Traversing Tests
*/
await benchmark<Cheerio<Element>>('traversing - Find', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.find('li').length,
});
await benchmark<Cheerio<Element>>('traversing - Parent', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.parent('div').length,
});
await benchmark<Cheerio<Element>>('traversing - Parents', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.parents('div').length,
});
await benchmark<Cheerio<Element>>('traversing - Closest', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.closest('div').length,
});
await benchmark<Cheerio<Element>>('traversing - next', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.next().length,
});
await benchmark<Cheerio<Element>>('traversing - nextAll', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.nextAll('li').length,
});
await benchmark<Cheerio<Element>>('traversing - nextUntil', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.nextUntil('li').length,
});
await benchmark<Cheerio<Element>>('traversing - prev', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.prev().length,
});
await benchmark<Cheerio<Element>>('traversing - prevAll', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.prevAll('li').length,
});
await benchmark<Cheerio<Element>>('traversing - prevUntil', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.prevUntil('li').length,
});
await benchmark<Cheerio<Element>>('traversing - siblings', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.siblings('li').length,
});
await benchmark<Cheerio<Element>>('traversing - Children', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.children('a').length,
});
await benchmark<Cheerio<Element>>('traversing - Filter', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.filter('li').length,
});
await benchmark<Cheerio<Element>>('traversing - First', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.first().first().length,
});
await benchmark<Cheerio<Element>>('traversing - Last', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.last().last().length,
});
await benchmark<Cheerio<Element>>('traversing - Eq', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.eq(0).eq(0).length,
});
/*
* Attributes Tests
*/
await benchmark<Cheerio<Element>>('attributes - Attributes', 'jquery.html', {
setup: ($) => $('li'),
test(_, $lis) {
$lis.attr('foo', 'bar');
$lis.attr('foo');
$lis.removeAttr('foo');
},
});
await benchmark<Cheerio<Element>>(
'attributes - Single Attribute',
'jquery.html',
{
setup: ($) => $('body'),
test(_, $lis) {
$lis.attr('foo', 'bar');
$lis.attr('foo');
$lis.removeAttr('foo');
},
},
);
await benchmark<Cheerio<Element>>('attributes - Data', 'jquery.html', {
setup: ($) => $('li'),
test(_, $lis) {
$lis.data('foo', 'bar');
$lis.data('foo');
},
});
await benchmark<Cheerio<Element>>('attributes - Val', 'jquery.html', {
setup: ($) => $('select,input,textarea,option'),
test($, $lis) {
$lis.each(function () {
$(this).val();
$(this).val('foo');
});
},
});
await benchmark<Cheerio<Element>>('attributes - Has class', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.hasClass('foo'),
});
await benchmark<Cheerio<Element>>('attributes - Toggle class', 'jquery.html', {
setup: ($) => $('li'),
test: (_, $lis) => $lis.toggleClass('foo'),
});
await benchmark<Cheerio<Element>>(
'attributes - Add Remove class',
'jquery.html',
{
setup: ($) => $('li'),
test(_, $lis) {
$lis.addClass('foo');
$lis.removeClass('foo');
},
},
);
================================================
FILE: benchmark/documents/jquery.html
================================================
<html
class="js multiplebgs boxshadow cssgradients wf-klavikaweb-i7-active wf-klavikaweb-n7-active wf-sourcecodepro-n4-active wf-sourcecodepro-n7-active wf-active"
lang="en-US"
>
<head data-live-domain="api.jquery.com">
<script type="text/javascript" async="" src="null"></script>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>jQuery() | jQuery API Documentation</title>
<meta name="author" content="jQuery Foundation - jquery.org" />
<meta
name="description"
content="jQuery: The Write Less, Do More, JavaScript Library"
/>
<meta name="viewport" content="width=device-width" />
<link
rel="shortcut icon"
href="http://api.jquery.com/jquery-wp-content/themes/api.jquery.com/i/favicon.ico"
src="null"
/>
<link
rel="stylesheet"
href="http://api.jquery.com/jquery-wp-content/themes/jquery/css/base.css?v=1"
src="null"
/>
<link
rel="stylesheet"
href="http://api.jquery.com/jquery-wp-content/themes/api.jquery.com/style.css"
src="null"
/>
<link rel="pingback" href="http://api.jquery.com/xmlrpc.php" src="null" />
<!--[if lt IE 7
]><link rel="stylesheet" href="css/font-awesome-ie7.min.css"
/><![endif]-->
<script type="text/javascript" async="" src="null"></script>
<script src="null"></script>
<script src="null"></script>
<script>
window.jQuery ||
document.write(
unescape(
'%3Cscript src="http://api.jquery.com/jquery-wp-content/themes/jquery/js/jquery-1.9.1.min.js"%3E%3C/script%3E'
)
);
</script>
<script src="null"></script>
<script src="null"></script>
<script src="null"></script>
<script src="null"></script>
<style type="text/css">
.tk-source-code-pro {
font-family: 'source-code-pro', sans-serif;
}
.tk-klavika-web {
font-family: 'klavika-web', sans-serif;
}
</style>
<link
rel="stylesheet"
href="http://use.typekit.net/c/d4d852/klavika-web:i7:n7,source-code-pro:n4:n7.PYh:F:2,PYg:F:2,Y1M:F:2,Y1P:F:2/d?3bb2a6e53c9684ffdc9a98f2135b2a6250f2340d8ca0853b7df9676f5fa610fe069f9d29c9b5e67ae7b6312a16ff95d3a73356eed53502d6630d88cb0fe9789e0ac2d9a6c14ac282069f97be80efceecd4f5e0e58b889e8649ff22efc0c4063e9f9f87c7a8920dcab32add3496e6b09e6a94141aaaeb81a4bb1d4a09b8a14ac46d7d0dff3bf6532c044b0313c5ed1d7226c76cac5039645b4082ff59a8953c4e06ef9a344cf9265e8de3ed48ac2f34b281583cbaf6f2f580f7709eba9ea284dc14f4722ed0e264d7faa135466fbba043f093297f0efc92bfcb7b3eb8761407436be31d8029117f1a72aa7b8b6319c956c739e1c25b7a993a45"
src="null"
/>
<script>
try {
Typekit.load();
} catch (_e) {}
</script>
<link
rel="alternate"
type="application/rss+xml"
title="jQuery API Documentation » Feed"
href="http://api.jquery.com/feed/"
src="null"
/>
<link
rel="alternate"
type="application/rss+xml"
title="jQuery API Documentation » Comments Feed"
href="http://api.jquery.com/comments/feed/"
src="null"
/>
<link
rel="alternate"
type="application/rss+xml"
title="jQuery API Documentation » jQuery() Comments Feed"
href="http://api.jquery.com/jQuery/feed/"
src="null"
/>
<script type="text/javascript" src="null"></script>
<link
rel="EditURI"
type="application/rsd+xml"
title="RSD"
href="http://api.jquery.com/xmlrpc.php?rsd"
src="null"
/>
<link
rel="wlwmanifest"
type="application/wlwmanifest+xml"
href="http://api.jquery.com/wp-includes/wlwmanifest.xml"
src="null"
/>
<link
rel="prev"
title="jQuery.holdReady()"
href="http://api.jquery.com/jQuery.holdReady/"
src="null"
/>
<link
rel="next"
title="jQuery.inArray()"
href="http://api.jquery.com/jQuery.inArray/"
src="null"
/>
<meta name="generator" content="WordPress 3.7" />
<link rel="canonical" href="http://api.jquery.com/jQuery/" src="null" />
<link rel="shortlink" href="http://api.jquery.com/?p=339" src="null" />
</head>
<body
class="api jquery single single-post postid-339 single-format-standard single-author singular"
>
<!--[if lt IE 7]>
<p class="chromeframe">
You are using an outdated browser.
<a href="http://browsehappy.com/">Upgrade your browser today</a>
or
<a href="http://www.google.com/chromeframe/?redirect=true"
>install Google Chrome Frame</a
>
to better experience this site.
</p>
<![endif]-->
<header>
<section id="global-nav">
<nav>
<div class="constrain">
<ul class="projects">
<li class="project jquery">
<a href="http://jquery.com/" title="jQuery" src="null"
>jQuery</a
>
</li>
<li class="project jquery-ui">
<a href="http://jqueryui.com/" title="jQuery UI" src="null"
>jQuery UI</a
>
</li>
<li class="project jquery-mobile">
<a
href="http://jquerymobile.com/"
title="jQuery Mobile"
src="null"
>jQuery Mobile</a
>
</li>
<li class="project sizzlejs">
<a href="http://sizzlejs.com/" title="Sizzle" src="null"
>Sizzle</a
>
</li>
<li class="project qunitjs">
<a href="http://qunitjs.com/" title="QUnit" src="null">QUnit</a>
</li>
</ul>
<ul class="links l_tinynav1">
<li>
<a href="http://plugins.jquery.com/" src="null">Plugins</a>
</li>
<li class="dropdown">
<a href="http://contribute.jquery.org/" src="null"
>Contribute</a
>
<ul>
<li>
<a href="http://contribute.jquery.org/cla/" src="null"
>CLA</a
>
</li>
<li>
<a
href="http://contribute.jquery.org/style-guide/"
src="null"
>Style Guides</a
>
</li>
<li>
<a href="http://contribute.jquery.org/triage/" src="null"
>Bug Triage</a
>
</li>
<li>
<a href="http://contribute.jquery.org/code/" src="null"
>Code</a
>
</li>
<li>
<a
href="http://contribute.jquery.org/documentation/"
src="null"
>Documentation</a
>
</li>
<li>
<a href="http://contribute.jquery.org/web-sites/" src="null"
>Web Sites</a
>
</li>
</ul>
</li>
<li class="dropdown">
<a href="http://events.jquery.org/" src="null">Events</a>
<ul class="wide">
<li>
<a
href="http://www.deque.com/deque-partners-jquery-create-accessibility-summit"
src="null"
>Oct 10-11 | jQuery Accessibility Summit</a
>
</li>
<li>
<a href="http://jquery.itmozg.ru/" src="null"
>Oct 15 | jQuery Russia</a
>
</li>
<li>
<a
href="http://modernweb.com/training/jquery-oct-2013.php"
src="null"
>Oct 15-17 | jQuery Virtual Training</a
>
</li>
<li>
<a href="http://2013.cssdevconf.com/" src="null"
>Oct 21-22 | CSS Dev Conf</a
>
</li>
<li>
<a href="http://javascriptsummit.com/" src="null"
>Nov 19-21 | JavaScript Summit</a
>
</li>
<li>
<a
href="http://events.jquery.org/2014/san-diego/"
src="null"
>Feb 12-13 | jQuery San Diego</a
>
</li>
<li>
<a href="http://www.gentics.com/jquery-europe" src="null"
>Feb 28-Mar 1 | jQuery Europe</a
>
</li>
<li>
<a href="http://jqueryuk.com" src="null"
>May 16 | jQuery UK</a
>
</li>
</ul>
</li>
<li class="dropdown">
<a href="https://jquery.org/support/" src="null">Support</a>
<ul>
<li>
<a href="http://learn.jquery.com/" src="null"
>Learning Center</a
>
</li>
<li>
<a href="http://try.jquery.com/" src="null">Try jQuery</a>
</li>
<li>
<a href="http://irc.jquery.org/" src="null">IRC/Chat</a>
</li>
<li>
<a href="http://forum.jquery.com/" src="null">Forums</a>
</li>
<li>
<a
href="http://stackoverflow.com/tags/jquery/info"
src="null"
>Stack Overflow</a
>
</li>
<li>
<a href="https://jquery.org/support/" src="null"
>Commercial Support</a
>
</li>
</ul>
</li>
<li class="dropdown">
<a href="https://jquery.org/" src="null">jQuery Foundation</a>
<ul>
<li>
<a href="https://jquery.org/join/" src="null">Join</a>
</li>
<li>
<a href="https://jquery.org/members/" src="null">Members</a>
</li>
<li>
<a href="https://jquery.org/team/" src="null">Team</a>
</li>
<li>
<a href="http://brand.jquery.org/" src="null"
>Brand Guide</a
>
</li>
<li>
<a href="https://jquery.org/donate/" src="null">Donate</a>
</li>
</ul>
</li>
</ul>
</div>
</nav>
</section>
</header>
<div id="container">
<div id="logo-events" class="constrain clearfix">
<h2 class="logo">
<a
href="http://jquery.com/"
title="jQuery API Documentation"
src="null"
>jQuery API Documentation</a
>
</h2>
<aside>
<div id="broadcast">
<a
href="http://engine.adzerk.net/r?e=eyJhdiI6MjIyMzYsImF0IjoxMzE0LCJjbSI6NjM3NjcsImNoIjo4MzY4LCJjciI6MTc4ODcxLCJkaSI6ImZhNDViODgwMzBhOTQxYzNhZmMyZTg0MmIwYzFiZDI1IiwiZG0iOjEsImZjIjoyMjgyOTgsImZsIjoxMTM1MjksImt3IjoidW5kZWZpbmVkIiwibnciOjU0NDksInJmIjoiaHR0cDovL2FwaS5qcXVlcnkuY29tLz9zPWpxdWVyeSIsInJ2IjowLCJwciI6MjE5MzcsInN0Ijo1MzgyOSwidHMiOjEzODU4Mzk5ODgyOTIsInVyIjoiaHR0cDovL2V2ZW50cy5qcXVlcnkub3JnLzIwMTQvc2FuLWRpZWdvLyJ9&s=pUb8fXw8Ar8bGvQszZJHXjkx8Gk"
rel="nofollow"
target="_blank"
title="jQuery San Diego"
src="null"
><img
src="null"
title="jQuery San Diego"
alt="jQuery San Diego"
border="0"
width="400"
height="100" /></a
><img height="0px" width="0px" border="0" src="null" alt="" />
</div>
</aside>
</div>
<nav id="main" class="constrain clearfix">
<div class="menu-top-container">
<ul id="menu-top" class="menu l_tinynav2">
<li class="menu-item">
<a href="http://jquery.com/download/" src="null">Download</a>
</li>
<li class="menu-item current">
<a href="http://api.jquery.com/" src="null">API Documentation</a>
</li>
<li class="menu-item">
<a href="http://blog.jquery.com/" src="null">Blog</a>
</li>
<li class="menu-item">
<a href="http://plugins.jquery.com/" src="null">Plugins</a>
</li>
<li class="menu-item">
<a href="http://jquery.com/browser-support/" src="null"
>Browser Support</a
>
</li>
</ul>
<select id="tinynav2" class="tinynav tinynav2"
><option>Navigate...</option
><option value="http://jquery.com/download/">Download</option
><option value="http://api.jquery.com/">API Documentation</option
><option value="http://blog.jquery.com/">Blog</option
><option value="http://plugins.jquery.com/">Plugins</option
><option value="http://jquery.com/browser-support/"
>Browser Support</option
></select
>
</div>
<form method="get" class="searchform" action="http://api.jquery.com/">
<button type="submit" class="icon-search">
<span class="visuallyhidden">search</span>
</button>
<label>
<span class="visuallyhidden">Search jQuery API Documentation</span>
<input type="text" name="s" value="" placeholder="Search" />
</label>
<label>
<span class="visuallyhidden">Search jQuery API Documentation</span>
<input type="radio" name="rad" value="" placeholder="Search" />
</label>
<label>
<span class="visuallyhidden">Search jQuery API Documentation</span>
<input type="radio" name="rad" value="foo" placeholder="Search" />
</label>
</form>
</nav>
<div id="content-wrapper" class="clearfix row">
<div class="content-right twelve columns">
<div id="content">
<article
id="post-339"
class="post-339 post type-post status-publish format-standard hentry category-core category-10 category-14"
>
<header class="entry-header">
<h1 class="entry-title">jQuery()</h1>
<hr />
<div class="entry-meta">
Categories:
<span class="category"
><a
href="http://api.jquery.com/category/core/"
title="View all posts in Core"
src="null"
>Core</a
></span
>
</div>
<!-- .entry-meta -->
</header>
<!-- .entry-header -->
<div class="entry-content">
Return a collection of matched elements either found in the DOM
based on passed argument(s) or created by passing an HTML
string.
<div class="toc">
<h4><span>Contents:</span></h4>
<ul class="toc-list">
<li>
<a href="#jQuery1" src="null"
>jQuery( selector [, context ] )</a
>
<ul>
<li>
<a href="#jQuery-selector-context" src="null"
>jQuery( selector [, context ] )</a
>
</li>
<li>
<a href="#jQuery-element" src="null"
>jQuery( element )</a
>
</li>
<li>
<a href="#jQuery-elementArray" src="null"
>jQuery( elementArray )</a
>
</li>
<li>
<a href="#jQuery-object" src="null"
>jQuery( object )</a
>
</li>
<li>
<a href="#jQuery-jQuery-object" src="null"
>jQuery( jQuery object )</a
>
</li>
<li>
<a href="#jQuery" src="null">jQuery()</a>
</li>
</ul>
</li>
<li>
<a href="#jQuery2" src="null"
>jQuery( html [, ownerDocument ] )</a
>
<ul>
<li>
<a href="#jQuery-html-ownerDocument" src="null"
>jQuery( html [, ownerDocument ] )</a
>
</li>
<li>
<a href="#jQuery-html-attributes" src="null"
>jQuery( html, attributes )</a
>
</li>
</ul>
</li>
<li>
<a href="#jQuery3" src="null">jQuery( callback )</a>
<ul>
<li>
<a href="#jQuery-callback" src="null"
>jQuery( callback )</a
>
</li>
</ul>
</li>
</ul>
</div>
<article id="jQuery1" class="entry method">
<h2 class="section-title">
<span class="name">jQuery( selector [, context ] )</span
><span class="returns"
>Returns:
<a href="http://api.jquery.com/Types/#jQuery" src="null"
>jQuery</a
></span
>
</h2>
<div class="entry-wrapper">
<p class="desc">
<strong>Description: </strong>Accepts a string containing
a CSS selector which is then used to match a set of
elements.
</p>
<ul class="signatures">
<li class="signature">
<h4 class="name">
<span class="version-details"
>version added:
<a href="/category/version/1.0/" src="null"
>1.0</a
></span
><a
id="jQuery-selector-context"
href="#jQuery-selector-context"
src="null"
><span class="icon-link"></span>jQuery( selector [,
context ] )</a
>
</h4>
<ul>
<li>
<div>
<strong>selector</strong>
</div>
<div>
Type:
<a
href="http://api.jquery.com/Types/#Selector"
src="null"
>Selector</a
>
</div>
<div>
A string containing a selector expression
</div>
</li>
<li>
<div>
<strong>context</strong>
</div>
<div>
Type:
<a
href="http://api.jquery.com/Types/#Element"
src="null"
>Element</a
>
or
<a
href="http://api.jquery.com/Types/#jQuery"
src="null"
>jQuery</a
>
</div>
<div>
A DOM Element, Document, or jQuery to use as
context
</div>
</li>
</ul>
</li>
<li class="signature">
<h4 class="name">
<span class="version-details"
>version added:
<a href="/category/version/1.0/" src="null"
>1.0</a
></span
><a
id="jQuery-element"
href="#jQuery-element"
src="null"
><span class="icon-link"></span>jQuery( element )</a
>
</h4>
<ul>
<li>
<div>
<strong>element</strong>
</div>
<div>
Type:
<a
href="http://api.jquery.com/Types/#Element"
src="null"
>Element</a
>
</div>
<div>
A DOM element to wrap in a jQuery object.
</div>
</li>
</ul>
</li>
<li class="signature">
<h4 class="name">
<span class="version-details"
>version added:
<a href="/category/version/1.0/" src="null"
>1.0</a
></span
><a
id="jQuery-elementArray"
href="#jQuery-elementArray"
src="null"
><span class="icon-link"></span>jQuery( elementArray
)</a
>
</h4>
<ul>
<li>
<div>
<strong>elementArray</strong>
</div>
<div>
Type:
<a
href="http://api.jquery.com/Types/#Array"
src="null"
>Array</a
>
</div>
<div>
An array containing a set of DOM elements to wrap
in a jQuery object.
</div>
</li>
</ul>
</li>
<li class="signature">
<h4 class="name">
<span class="version-details"
>version added:
<a href="/category/version/1.0/" src="null"
>1.0</a
></span
><a
id="jQuery-object"
href="#jQuery-object"
src="null"
><span class="icon-link"></span>jQuery( object )</a
>
</h4>
<ul>
<li>
<div>
<strong>object</strong>
</div>
<div>
Type:
<a
href="http://api.jquery.com/Types/#PlainObject"
src="null"
>PlainObject</a
>
</div>
<div>
A plain object to wrap in a jQuery object.
</div>
</li>
</ul>
</li>
<li class="signature">
<h4 class="name">
<span class="version-details"
>version added:
<a href="/category/version/1.0/" src="null"
>1.0</a
></span
><a
id="jQuery-jQuery-object"
href="#jQuery-jQuery-object"
src="null"
><span class="icon-link"></span>jQuery( jQuery
object )</a
>
</h4>
<ul>
<li>
<div>
<strong>jQuery object</strong>
</div>
<div>
Type:
<a
href="http://api.jquery.com/Types/#PlainObject"
src="null"
>PlainObject</a
>
</div>
<div>
An existing jQuery object to clone.
</div>
</li>
</ul>
</li>
<li class="signature">
<h4 class="name">
<span class="version-details"
>version added:
<a href="/category/version/1.4/" src="null"
>1.4</a
></span
><a id="jQuery" href="#jQuery" src="null"
><span class="icon-link"></span>jQuery()</a
>
</h4>
<ul>
<li>
<div class="null-signature">
This signature does not accept any arguments.
</div>
</li>
</ul>
</li>
</ul>
<div class="longdesc" id="entry-longdesc">
<p>
In the first formulation listed above,
<code>jQuery()</code> — which can also be written as
<code>$()</code> — searches through the DOM for any
elements that match the provided selector and creates a
new jQuery object that references these elements:
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"div.foo"</span> );</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>
If no elements match the provided selector, the new
jQuery object is "empty"; that is, it contains no
elements and has
<code><a href="/length/" src="null">.length</a></code>
property of 0.
</p>
<h4 id="selector-context">
Selector Context
</h4>
<p>
By default, selectors perform their searches within the
DOM starting at the document root. However, an alternate
context can be given for the search by using the
optional second parameter to the
<code>$()</code> function. For example, to do a search
within an event handler, the search can be restricted
like so:
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
<div class="line n3">
3
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"div.foo"</span> ).click(<span class="keyword">function</span>() {</code></div></div><div class="container"><div class="line"><code> $( <span class="string">"span"</span>, <span class="keyword">this</span> ).addClass( <span class="string">"bar"</span> );</code></div></div><div class="container"><div class="line"><code>});</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>
When the search for the span selector is restricted to
the context of <code>this</code>, only spans within the
clicked element will get the additional class.
</p>
<p>
Internally, selector context is implemented with the
<code>.find()</code> method, so
<code>$( "span", this )</code>
is equivalent to
<code>$( this ).find( "span" )</code>.
</p>
<h4 id="using-dom-elements">
Using DOM elements
</h4>
<p>
The second and third formulations of this function
create a jQuery object using one or more DOM elements
that were already selected in some other way.
</p>
<p>
<strong>Note:</strong> These formulations are meant to
consume only DOM elements; feeding mixed data to the
elementArray form is particularly discouraged.
</p>
<p>
A common use of this facility is to call jQuery methods
on an element that has been passed to a callback
function through the keyword <code>this</code>:
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
<div class="line n3">
3
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"div.foo"</span> ).click(<span class="keyword">function</span>() {</code></div></div><div class="container"><div class="line"><code> $( <span class="keyword">this</span> ).slideUp();</code></div></div><div class="container"><div class="line"><code>});</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>
This example causes elements to be hidden with a sliding
animation when clicked. Because the handler receives the
clicked item in the
<code>this</code> keyword as a bare DOM element, the
element must be passed to the <code>$()</code> function
before applying jQuery methods to it.
</p>
<p>
XML data returned from an Ajax call can be passed to the
<code>$()</code> function so individual elements of the
XML structure can be retrieved using
<code>.find()</code> and other DOM traversal methods.
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
<div class="line n3">
3
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$.post( <span class="string">"url.xml"</span>, <span class="keyword">function</span>( data ) {</code></div></div><div class="container"><div class="line"><code> <span class="keyword">var</span> $child = $( data ).find( <span class="string">"child"</span> );</code></div></div><div class="container"><div class="line"><code>});</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
<h4 id="cloning-jquery-objects">
Cloning jQuery Objects
</h4>
<p>
When a jQuery object is passed to the
<code>$()</code> function, a clone of the object is
created. This new jQuery object references the same DOM
elements as the initial one.
</p>
<h4 id="returning-empty-set">
Returning an Empty Set
</h4>
<p>
As of jQuery 1.4, calling the
<code>jQuery()</code> method with
<em>no arguments</em> returns an empty jQuery set (with
a
<code><a href="/length/" src="null">.length</a></code>
property of 0). In previous versions of jQuery, this
would return a set containing the document node.
</p>
<h4 id="working-with-plain-objects">
Working With Plain Objects
</h4>
<p>
At present, the only operations supported on plain
JavaScript objects wrapped in jQuery are:
<code>.data()</code
>,<code>.prop()</code>,<code>.on()</code>,
<code>.off()</code>, <code>.trigger()</code> and
<code>.triggerHandler()</code>. The use of
<code>.data()</code> (or any method requiring
<code>.data()</code>) on a plain object will result in a
new property on the object called jQuery{randomNumber}
(eg. jQuery123456789).
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
<div class="line n3">
3
</div>
<div class="line n4">
4
</div>
<div class="line n5">
5
</div>
<div class="line n6">
6
</div>
<div class="line n7">
7
</div>
<div class="line n8">
8
</div>
<div class="line n9">
9
</div>
<div class="line n10">
10
</div>
<div class="line n11">
11
</div>
<div class="line n12">
12
</div>
<div class="line n13">
13
</div>
<div class="line n14">
14
</div>
<div class="line n15">
15
</div>
<div class="line n16">
16
</div>
<div class="line n17">
17
</div>
<div class="line n18">
18
</div>
<div class="line n19">
19
</div>
<div class="line n20">
20
</div>
<div class="line n21">
21
</div>
<div class="line n22">
22
</div>
<div class="line n23">
23
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code><span class="comment">// Define a plain object</span></code></div></div><div class="container"><div class="line"><code><span class="keyword">var</span> foo = { foo: <span class="string">"bar"</span>, hello: <span class="string">"world"</span> };</code></div></div><div class="container"><div class="line"><code> </code></div></div><div class="container"><div class="line"><code><span class="comment">// Pass it to the jQuery function</span></code></div></div><div class="container"><div class="line"><code><span class="keyword">var</span> $foo = $( foo );</code></div></div><div class="container"><div class="line"><code> </code></div></div><div class="container"><div class="line"><code><span class="comment">// Test accessing property values</span></code></div></div><div class="container"><div class="line"><code><span class="keyword">var</span> test1 = $foo.prop( <span class="string">"foo"</span> ); <span class="comment">// bar</span></code></div></div><div class="container"><div class="line"><code> </code></div></div><div class="container"><div class="line"><code><span class="comment">// Test setting property values</span></code></div></div><div class="container"><div class="line"><code>$foo.prop( <span class="string">"foo"</span>, <span class="string">"foobar"</span> );</code></div></div><div class="container"><div class="line"><code><span class="keyword">var</span> test2 = $foo.prop( <span class="string">"foo"</span> ); <span class="comment">// foobar</span></code></div></div><div class="container"><div class="line"><code> </code></div></div><div class="container"><div class="line"><code><span class="comment">// Test using .data() as summarized above</span></code></div></div><div class="container"><div class="line"><code>$foo.data( <span class="string">"keyName"</span>, <span class="string">"someValue"</span> );</code></div></div><div class="container"><div class="line"><code>console.log( $foo ); <span class="comment">// will now contain a jQuery{randomNumber} property</span></code></div></div><div class="container"><div class="line"><code> </code></div></div><div class="container"><div class="line"><code><span class="comment">// Test binding an event name and triggering</span></code></div></div><div class="container"><div class="line"><code>$foo.on( <span class="string">"eventName"</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span></code></div></div><div class="container"><div class="line"><code> console.log( <span class="string">"eventName was called"</span> );</code></div></div><div class="container"><div class="line"><code>});</code></div></div><div class="container"><div class="line"><code> </code></div></div><div class="container"><div class="line"><code>$foo.trigger( <span class="string">"eventName"</span> ); <span class="comment">// Logs "eventName was called"</span></code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>
Should
<code>.trigger( "eventName" )</code>
be used, it will search for an "eventName" property on
the object and attempt to execute it after any attached
jQuery handlers are executed. It does not check whether
the property is a function or not. To avoid this
behavior,
<code>.triggerHandler( "eventName" )</code>
should be used instead.
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$foo.triggerHandler( <span class="string">"eventName"</span> ); <span class="comment">// Also logs "eventName was called"</span></code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<section class="entry-examples" id="entry-examples">
<header><h2>Examples:</h2></header>
<div class="entry-example" id="example-0">
<h4>
Example:
<span class="desc"
>Find all p elements that are children of a div
element and apply a border to them.</span
>
</h4>
<div class="syntaxhighlighter xml">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
<div class="line n3">
3
</div>
<div class="line n4">
4
</div>
<div class="line n5">
5
</div>
<div class="line n6">
6
</div>
<div class="line n7">
7
</div>
<div class="line n8">
8
</div>
<div class="line n9">
9
</div>
<div class="line n10">
10
</div>
<div class="line n11">
11
</div>
<div class="line n12">
12
</div>
<div class="line n13">
13
</div>
<div class="line n14">
14
</div>
<div class="line n15">
15
</div>
<div class="line n16">
16
</div>
<div class="line n17">
17
</div>
<div class="line n18">
18
</div>
<div class="line n19">
19
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code><span class="doctype"><!doctype html></span></code></div></div><div class="container"><div class="line"><code><span class="tag"><<span class="title">html</span> <span class="attribute">lang</span>=<span class="value">"en"</span>></span></code></div></div><div class="container"><div class="line"><code><span class="tag"><<span class="title">head</span>></span></code></div></div><div class="container"><div class="line"><code> <span class="tag"><<span class="title">meta</span> <span class="attribute">charset</span>=<span class="value">"utf-8"</span>></span></code></div></div><div class="container"><div class="line"><code> <span class="tag"><<span class="title">title</span>></span>jQuery demo<span class="tag"></<span class="title">title</span>></span></code></div></div><div class="container"><div class="line"><code> <span class="tag"><<span class="title">script</span> <span class="attribute">src</span>=<span class="value">"http://code.jquery.com/jquery-1.9.1.js"</span>></span><span class="javascript"></span><span class="tag"></<span class="title">script</span>></span></code></div></div><div class="container"><div class="line"><code><span class="tag"></<span class="title">head</span>></span></code></div></div><div class="container"><div class="line"><code><span class="tag"><<span class="title">body</span>></span></code></div></div><div class="container"><div class="line"><code> </code></div></div><div class="container"><div class="line"><code><span class="tag"><<span class="title">p</span>></span>one<span class="tag"></<span class="title">p</span>></span></code></div></div><div class="container"><div class="line"><code><span class="tag"><<span class="title">div</span>></span><span class="tag"><<span class="title">p</span>></span>two<span class="tag"></<span class="title">p</span>></span><span class="tag"></<span class="title">div</span>></span></code></div></div><div class="container"><div class="line"><code><span class="tag"><<span class="title">p</span>></span>three<span class="tag"></<span class="title">p</span>></span></code></div></div><div class="container"><div class="line"><code> </code></div></div><div class="container"><div class="line"><code><span class="tag"><<span class="title">script</span>></span><span class="javascript"></span></code></div></div><div class="container"><div class="line"><code>$( <span class="string">"div > p"</span> ).css( <span class="string">"border"</span>, <span class="string">"1px solid gray"</span> );</code></div></div><div class="container"><div class="line"><code><span class="tag"></<span class="title">script</span>></span></code></div></div><div class="container"><div class="line"><code> </code></div></div><div class="container"><div class="line"><code><span class="tag"></<span class="title">body</span>></span></code></div></div><div class="container"><div class="line"><code><span class="tag"></<span class="title">html</span>></span></code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
<h4>Demo:</h4>
<div class="demo code-demo">
<iframe width="100%" height="250" title="Demo"></iframe>
</div>
</div>
<div class="entry-example" id="example-1">
<h4>
Example:
<span class="desc"
>Find all inputs of type radio within the first form
in the document.</span
>
</h4>
<div class="syntaxhighlighter javascript">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"input:radio"</span>, document.forms[ <span class="number">0</span> ] );</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="entry-example" id="example-2">
<h4>
Example:
<span class="desc"
>Find all div elements within an XML document from
an Ajax response.</span
>
</h4>
<div class="syntaxhighlighter javascript">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"div"</span>, xml.responseXML );</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="entry-example" id="example-3">
<h4>
Example:
<span class="desc"
>Set the background color of the page to
black.</span
>
</h4>
<div class="syntaxhighlighter javascript">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( document.body ).css( <span class="string">"background"</span>, <span class="string">"black"</span> );</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="entry-example" id="example-4">
<h4>
Example:
<span class="desc"
>Hide all the input elements within a form.</span
>
</h4>
<div class="syntaxhighlighter javascript">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( myForm.elements ).hide();</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</div>
</article>
<article id="jQuery2" class="entry method">
<h2 class="section-title">
<span class="name">jQuery( html [, ownerDocument ] )</span
><span class="returns"
>Returns:
<a href="http://api.jquery.com/Types/#jQuery" src="null"
>jQuery</a
></span
>
</h2>
<div class="entry-wrapper">
<p class="desc">
<strong>Description: </strong>Creates DOM elements on the
fly from the provided string of raw HTML.
</p>
<ul class="signatures">
<li class="signature">
<h4 class="name">
<span class="version-details"
>version added:
<a href="/category/version/1.0/" src="null"
>1.0</a
></span
><a
id="jQuery-html-ownerDocument"
href="#jQuery-html-ownerDocument"
src="null"
><span class="icon-link"></span>jQuery( html [,
ownerDocument ] )</a
>
</h4>
<ul>
<li>
<div>
<strong>html</strong>
</div>
<div>
Type:
<a
href="http://api.jquery.com/Types/#htmlString"
src="null"
>htmlString</a
>
</div>
<div>
A string of HTML to create on the fly. Note that
this parses HTML,
<strong>not</strong>
XML.
</div>
</li>
<li>
<div>
<strong>ownerDocument</strong>
</div>
<div>
Type:
<a
href="http://api.jquery.com/Types/#document"
src="null"
>document</a
>
</div>
<div>
A document in which the new elements will be
created.
</div>
</li>
</ul>
</li>
<li class="signature">
<h4 class="name">
<span class="version-details"
>version added:
<a href="/category/version/1.4/" src="null"
>1.4</a
></span
><a
id="jQuery-html-attributes"
href="#jQuery-html-attributes"
src="null"
><span class="icon-link"></span>jQuery( html,
attributes )</a
>
</h4>
<ul>
<li>
<div>
<strong>html</strong>
</div>
<div>
Type:
<a
href="http://api.jquery.com/Types/#htmlString"
src="null"
>htmlString</a
>
</div>
<div>
A string defining a single, standalone, HTML
element (e.g. <div/> or
<div></div>).
</div>
</li>
<li>
<div>
<strong>attributes</strong>
</div>
<div>
Type:
<a
href="http://api.jquery.com/Types/#PlainObject"
src="null"
>PlainObject</a
>
</div>
<div>
An object of attributes, events, and methods to
call on the newly-created element.
</div>
</li>
</ul>
</li>
</ul>
<div class="longdesc" id="entry-longdesc-1">
<h4 id="creating-new-elements">
Creating New Elements
</h4>
<p>
If a string is passed as the parameter to
<code>$()</code>, jQuery examines the string to see if
it looks like HTML (i.e., it starts with
<code><tag ... ></code>). If not, the string is
interpreted as a selector expression, as explained
above. But if the string appears to be an HTML snippet,
jQuery attempts to create new DOM elements as described
by the HTML. Then a jQuery object is created and
returned that refers to these elements. You can perform
any of the usual jQuery methods on this object:
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"<p id='test'>My <em>new</em> text</p>"</span> ).appendTo( <span class="string">"body"</span> );</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>
For explicit parsing of a string to HTML, use the
<a href="/jQuery.parseHTML/" src="null"
>$.parseHTML()</a
>
method.
</p>
<p>
By default, elements are created with an
<code>ownerDocument</code>
matching the document into which the jQuery library was
loaded. Elements being injected into a different
document should be created using that document, e.g.,
<code
>$("<p>hello iframe</p>",
$("#myiframe").prop("contentWindow").document)</code
>.
</p>
<p>
If the HTML is more complex than a single tag without
attributes, as it is in the above example, the actual
creation of the elements is handled by the browser's
<code>innerHTML</code>
mechanism. In most cases, jQuery creates a new
<div> element and sets the innerHTML property of
the element to the HTML snippet that was passed in. When
the parameter has a single tag (with optional closing
tag or quick-closing) —
<code>$( "<img />" )</code>
or
<code>$( "<img>" )</code>,
<code>$( "<a></a>" )</code>
or
<code>$( "<a>" )</code> — jQuery creates the
element using the native JavaScript
<code>createElement()</code>
function.
</p>
<p>
When passing in complex HTML, some browsers may not
generate a DOM that exactly replicates the HTML source
provided. As mentioned, jQuery uses the browser"s
<code>.innerHTML</code> property to parse the passed
HTML and insert it into the current document. During
this process, some browsers filter out certain elements
such as <code><html></code>,
<code><title></code>, or
<code><head></code>
elements. As a result, the elements inserted may not be
representative of the original string passed.
</p>
<p>
Filtering isn't, however, limited to these tags. For
example, Internet Explorer prior to version 8 will also
convert all <code>href</code> properties on links to
absolute URLs, and Internet Explorer prior to version 9
will not correctly handle HTML5 elements without the
addition of a separate
<a href="http://code.google.com/p/html5shiv/" src="null"
>compatibility layer</a
>.
</p>
<p>
To ensure cross-platform compatibility, the snippet must
be well-formed. Tags that can contain other elements
should be paired with a closing tag:
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"<a href='http://jquery.com'></a>"</span> );</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>
Tags that cannot contain elements may be quick-closed or
not:
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"<img>"</span> );</code></div></div><div class="container"><div class="line"><code>$( <span class="string">"<input>"</span> );</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>
When passing HTML to
<code>jQuery()</code>, please also note that text nodes
are not treated as DOM elements. With the exception of a
few methods (such as <code>.content()</code>), they are
generally otherwise ignored or removed. E.g:
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code><span class="keyword">var</span> el = $( <span class="string">"1<br>2<br>3"</span> ); <span class="comment">// returns [<br>, "2", <br>]</span></code></div></div><div class="container"><div class="line"><code>el = $( <span class="string">"1<br>2<br>3 >"</span> ); <span class="comment">// returns [<br>, "2", <br>, "3 &gt;"]</span></code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>This behavior is expected.</p>
<p>
As of jQuery 1.4, the second argument to
<code>jQuery()</code> can accept a plain object
consisting of a superset of the properties that can be
passed to the
<a href="/attr/" src="null">.attr()</a>
method.
</p>
<p>
<strong>Important:</strong> If the second argument is
passed, the HTML string in the first argument must
represent a a simple element with no attributes.
<strong>As of jQuery 1.4</strong>, any
<a href="/category/events/" src="null">event type</a>
can be passed in, and the following jQuery methods can
be called:
<a href="/val/" src="null">val</a>,
<a href="/css/" src="null">css</a>,
<a href="/html/" src="null">html</a>,
<a href="/text/" src="null">text</a>,
<a href="/data/" src="null">data</a>,
<a href="/width/" src="null">width</a>,
<a href="/height/" src="null">height</a>, or
<a href="/offset/" src="null">offset</a>.
</p>
<p>
<strong>As of jQuery 1.8</strong>, any jQuery instance
method (a method of <code>jQuery.fn</code>) can be used
as a property of the object passed to the second
parameter:
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
<div class="line n3">
3
</div>
<div class="line n4">
4
</div>
<div class="line n5">
5
</div>
<div class="line n6">
6
</div>
<div class="line n7">
7
</div>
<div class="line n8">
8
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"<div></div>"</span>, {</code></div></div><div class="container"><div class="line"><code> <span class="string">"class"</span>: <span class="string">"my-div"</span>,</code></div></div><div class="container"><div class="line"><code> on: {</code></div></div><div class="container"><div class="line"><code> touchstart: <span class="keyword">function</span>( event ) {</code></div></div><div class="container"><div class="line"><code> <span class="comment">// Do something</span></code></div></div><div class="container"><div class="line"><code> }</code></div></div><div class="container"><div class="line"><code> }</code></div></div><div class="container"><div class="line"><code>}).appendTo( <span class="string">"body"</span> );</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>
The name
<code>"class"</code> must be quoted in the object since
it is a JavaScript reserved word, and
<code>"className"</code> cannot be used since it refers
to the DOM property, not the attribute.
</p>
<p>
While the second argument is convenient, its flexibility
can lead to unintended consequences (e.g.
<code>$( "<input>", {size: "4"} )</code>
calling the
<code>.size()</code> method instead of setting the size
attribute). The previous code block could thus be
written instead as:
</p>
<div class="syntaxhighlighter javascript nogutter">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
<div class="line n3">
3
</div>
<div class="line n4">
4
</div>
<div class="line n5">
5
</div>
<div class="line n6">
6
</div>
<div class="line n7">
7
</div>
<div class="line n8">
8
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"<div></div>"</span> )</code></div></div><div class="container"><div class="line"><code> .addClass( <span class="string">"my-div"</span> )</code></div></div><div class="container"><div class="line"><code> .on({</code></div></div><div class="container"><div class="line"><code> touchstart: <span class="keyword">function</span>( event ) {</code></div></div><div class="container"><div class="line"><code> <span class="comment">// Do something</span></code></div></div><div class="container"><div class="line"><code> }</code></div></div><div class="container"><div class="line"><code> })</code></div></div><div class="container"><div class="line"><code> .appendTo( <span class="string">"body"</span> );</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<section class="entry-examples" id="entry-examples-1">
<header><h2>Examples:</h2></header>
<div class="entry-example" id="example-1-0">
<h4>
Example:
<span class="desc"
>Create a div element (and all of its contents)
dynamically and append it to the body element.
Internally, an element is created and its innerHTML
property set to the given markup.</span
>
</h4>
<div class="syntaxhighlighter javascript">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"<div><p>Hello</p></div>"</span> ).appendTo( <span class="string">"body"</span> )</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="entry-example" id="example-1-1">
<h4>
Example:
<span class="desc">Create some DOM elements.</span>
</h4>
<div class="syntaxhighlighter javascript">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
<div class="line n3">
3
</div>
<div class="line n4">
4
</div>
<div class="line n5">
5
</div>
<div class="line n6">
6
</div>
<div class="line n7">
7
</div>
<div class="line n8">
8
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$( <span class="string">"<div/>"</span>, {</code></div></div><div class="container"><div class="line"><code> <span class="string">"class"</span>: <span class="string">"test"</span>,</code></div></div><div class="container"><div class="line"><code> text: <span class="string">"Click me!"</span>,</code></div></div><div class="container"><div class="line"><code> click: <span class="keyword">function</span>() {</code></div></div><div class="container"><div class="line"><code> $( <span class="keyword">this</span> ).toggleClass( <span class="string">"test"</span> );</code></div></div><div class="container"><div class="line"><code> }</code></div></div><div class="container"><div class="line"><code>})</code></div></div><div class="container"><div class="line"><code> .appendTo( <span class="string">"body"</span> );</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</div>
</article>
<article id="jQuery3" class="entry method">
<h2 class="section-title">
<span class="name">jQuery( callback )</span
><span class="returns"
>Returns:
<a href="http://api.jquery.com/Types/#jQuery" src="null"
>jQuery</a
></span
>
</h2>
<div class="entry-wrapper">
<p class="desc">
<strong>Description: </strong>Binds a function to be
executed when the DOM has finished loading.
</p>
<ul class="signatures">
<li class="signature">
<h4 class="name">
<span class="version-details"
>version added:
<a href="/category/version/1.0/" src="null"
>1.0</a
></span
><a
id="jQuery-callback"
href="#jQuery-callback"
src="null"
><span class="icon-link"></span>jQuery( callback
)</a
>
</h4>
<ul>
<li>
<div>
<strong>callback</strong>
</div>
<div>
Type:
<a
href="http://api.jquery.com/Types/#Function"
src="null"
>Function</a
>()
</div>
<div>
The function to execute when the DOM is ready.
</div>
</li>
</ul>
</li>
</ul>
<div class="longdesc" id="entry-longdesc-2">
<p>
This function behaves just like
<code>$( document ).ready()</code>, in that it should be
used to wrap other <code>$()</code> operations on your
page that depend on the DOM being ready. While this
function is, technically, chainable, there really isn"t
much use for chaining against it.
</p>
</div>
<section class="entry-examples" id="entry-examples-2">
<header><h2>Examples:</h2></header>
<div class="entry-example" id="example-2-0">
<h4>
Example:
<span class="desc"
>Execute the function when the DOM is ready to be
used.</span
>
</h4>
<div class="syntaxhighlighter javascript">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
<div class="line n3">
3
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>$(<span class="keyword">function</span>() {</code></div></div><div class="container"><div class="line"><code> <span class="comment">// Document is ready</span></code></div></div><div class="container"><div class="line"><code>});</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="entry-example" id="example-2-1">
<h4>
Example:
<span class="desc"
>Use both the shortcut for $(document).ready() and
the argument to write failsafe jQuery code using the
$ alias, without relying on the global alias.</span
>
</h4>
<div class="syntaxhighlighter javascript">
<table>
<tbody>
<tr>
<td class="gutter">
<div class="line n1">
1
</div>
<div class="line n2">
2
</div>
<div class="line n3">
3
</div>
</td>
<td class="code">
<pre><div class="container"><div class="line"><code>jQuery(<span class="keyword">function</span>( $ ) {</code></div></div><div class="container"><div class="line"><code> <span class="comment">// Your code using failsafe $ alias here...</span></code></div></div><div class="container"><div class="line"><code>});</code></div></div></pre>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</div>
</article>
</div>
<!-- .entry-content -->
</article>
<!-- #post-339 -->
</div>
<div id="sidebar" class="widget-area" role="complementary">
<aside id="categories" class="widget">
<ul>
<li class="cat-item cat-item-1">
<a
href="http://api.jquery.com/category/ajax/"
title="View all posts filed under Ajax"
src="null"
>Ajax</a
>
<ul class="children">
<li class="cat-item cat-item-2">
<a
href="http://api.jquery.com/category/ajax/global-ajax-event-handlers/"
title="View all posts filed under Global Ajax Event Handlers"
src="null"
>Global Ajax Event Handlers</a
>
</li>
<li class="cat-item cat-item-3">
<a
href="http://api.jquery.com/category/ajax/helper-functions/"
title="View all posts filed under Helper Functions"
src="null"
>Helper Functions</a
>
</li>
<li class="cat-item cat-item-4">
<a
href="http://api.jquery.com/category/ajax/low-level-interface/"
title="View all posts filed under Low-Level Interface"
src="null"
>Low-Level Interface</a
>
</li>
<li class="cat-item cat-item-5">
<a
href="http://api.jquery.com/category/ajax/shorthand-methods/"
title="View all posts filed under Shorthand Methods"
src="null"
>Shorthand Methods</a
>
</li>
</ul>
</li>
<li class="cat-item cat-item-6">
<a
href="http://api.jquery.com/category/attributes/"
title="View all posts filed under Attributes"
src="null"
>Attributes</a
>
</li>
<li class="cat-item cat-item-7">
<a
href="http://api.jquery.com/category/callbacks-object/"
title="View all posts filed under Callbacks Object"
src="null"
>Callbacks Object</a
>
</li>
<li class="cat-item cat-item-8 current-cat">
<a
href="http://api.jquery.com/category/core/"
title="View all posts filed under Core"
src="null"
>Core</a
>
</li>
<li class="cat-item cat-item-9">
<a
href="http://api.jquery.com/category/css/"
title="View all posts filed under CSS"
src="null"
>CSS</a
>
</li>
<li class="cat-item cat-item-10">
<a
href="http://api.jquery.com/category/data/"
title="View all posts filed under Data"
src="null"
>Data</a
>
</li>
<li class="cat-item cat-item-11">
<a
href="http://api.jquery.com/category/deferred-object/"
title="View all posts filed under Deferred Object"
src="null"
>Deferred Object</a
>
</li>
<li class="cat-item cat-item-87">
<a
href="http://api.jquery.com/category/deprecated/"
title="View all posts filed under Deprecated"
src="null"
>Deprecated</a
>
<ul class="children">
<li class="cat-item cat-item-93">
<a
href="http://api.jquery.com/category/deprecated/deprecated-1.10/"
title="View all posts filed under Deprecated 1.10"
src="null"
>Deprecated 1.10</a
>
</li>
<li class="cat-item cat-item-90">
<a
href="http://api.jquery.com/category/deprecated/deprecated-1.3/"
title="View all posts filed under Deprecated 1.3"
src="null"
>Deprecated 1.3</a
>
</li>
<li class="cat-item cat-item-88">
<a
href="http://api.jquery.com/category/deprecated/deprecated-1.7/"
title="View all posts filed under Deprecated 1.7"
src="null"
>Deprecated 1.7</a
>
</li>
<li class="cat-item cat-item-89">
<a
href="http://api.jquery.com/category/deprecated/deprecated-1.8/"
title="View all posts filed under Deprecated 1.8"
src="null"
>Deprecated 1.8</a
>
</li>
</ul>
</li>
<li class="cat-item cat-item-12">
<a
href="http://api.jquery.com/category/dimensions/"
title="View all posts filed under Dimensions"
src="null"
>Dimensions</a
>
</li>
<li class="cat-item cat-item-13">
<a
href="http://api.jquery.com/category/effects/"
title="View all posts filed under Effects"
src="null"
>Effects</a
>
<ul class="children">
<li class="cat-item cat-item-14">
<a
href="http://api.jquery.com/category/effects/basics/"
title="View all posts filed under Basics"
src="null"
>Basics</a
>
</li>
<li class="cat-item cat-item-15">
<a
href="http://api.jquery.com/category/effects/custom-effects/"
title="View all posts filed under Custom"
src="null"
>Custom</a
>
</li>
<li class="cat-item cat-item-16">
<a
href="http://api.jquery.com/category/effects/fading/"
title="View all posts filed under Fading"
src="null"
>Fading</a
>
</li>
<li class="cat-item cat-item-17">
<a
href="http://api.jquery.com/category/effects/sliding/"
title="View all posts filed under Sliding"
src="null"
>Sliding</a
>
</li>
</ul>
</li>
<li class="cat-item cat-item-18">
<a
href="http://api.jquery.com/category/events/"
title="View all posts filed under Events"
src="null"
>Events</a
>
<ul class="children">
<li class="cat-item cat-item-19">
<a
href="http://api.jquery.com/category/events/browser-events/"
title="View all posts filed under Browser Events"
src="null"
>Browser Events</a
>
</li>
<li class="cat-item cat-item-20">
<a
href="http://api.jquery.com/category/events/document-loading/"
title="View all posts filed under Document Loading"
src="null"
>Document Loading</a
>
</li>
<li class="cat-item cat-item-21">
<a
href="http://api.jquery.com/category/events/event-handler-attachment/"
title="View all posts filed under Event Handler Attachment"
src="null"
>Event Handler Attachment</a
>
</li>
<li class="cat-item cat-item-22">
<a
href="http://api.jquery.com/category/events/event-object/"
title="View all posts filed under Event Object"
src="null"
>Event Object</a
>
</li>
<li class="cat-item cat-item-23">
<a
href="http://api.jquery.com/category/events/form-events/"
title="View all posts filed under Form Events"
src="null"
>Form Events</a
>
</li>
<li class="cat-item cat-item-24">
<a
href="http://api.jquery.com/category/events/keyboard-events/"
title="View all posts filed under Keyboard Events"
src="null"
>Keyboard Events</a
>
</li>
<li class="cat-item cat-item-25">
<a
href="http://api.jquery.com/category/events/mouse-events/"
title="View all posts filed under Mouse Events"
src="null"
>Mouse Events</a
>
</li>
</ul>
</li>
<li class="cat-item cat-item-26">
<a
href="http://api.jquery.com/category/forms/"
title="View all posts filed under Forms"
src="null"
>Forms</a
>
</li>
<li class="cat-item cat-item-27">
<a
href="http://api.jquery.com/category/internals/"
title="View all posts filed under Internals"
src="null"
>Internals</a
>
</li>
<li class="cat-item cat-item-28">
<a
href="http://api.jquery.com/category/manipulation/"
title="View all posts filed under Manipulation"
src="null"
>Manipulation</a
>
<ul class="children">
<li class="cat-item cat-item-29">
<a
href="http://api.jquery.com/category/manipulation/class-attribute/"
title="View all posts filed under Class Attribute"
src="null"
>Class Attribute</a
>
</li>
<li class="cat-item cat-item-30">
<a
href="http://api.jquery.com/category/manipulation/copying/"
title="View all posts filed under Copying"
src="null"
>Copying</a
>
</li>
<li class="cat-item cat-item-32">
<a
href="http://api.jquery.com/category/manipulation/dom-insertion-around/"
title="View all posts filed under DOM Insertion, Around"
src="null"
>DOM Insertion, Around</a
>
</li>
<li class="cat-item cat-item-33">
<a
href="http://api.jquery.com/category/manipulation/dom-insertion-inside/"
title="View all posts filed under DOM Insertion, Inside"
src="null"
>DOM Insertion, Inside</a
>
</li>
<li class="cat-item cat-item-34">
<a
href="http://api.jquery.com/category/manipulation/dom-insertion-outside/"
title="View all posts filed under DOM Insertion, Outside"
src="null"
>DOM Insertion, Outside</a
>
</li>
<li class="cat-item cat-item-35">
<a
href="http://api.jquery.com/category/manipulation/dom-removal/"
title="View all posts filed under DOM Removal"
src="null"
>DOM Removal</a
>
</li>
<li class="cat-item cat-item-36">
<a
href="http://api.jquery.com/category/manipulation/dom-replacement/"
title="View all posts filed under DOM Replacement"
src="null"
>DOM Replacement</a
>
</li>
<li class="cat-item cat-item-37">
<a
href="http://api.jquery.com/category/manipulation/general-attributes/"
title="View all posts filed under General Attributes"
src="null"
>General Attributes</a
>
</li>
<li class="cat-item cat-item-38">
<a
href="http://api.jquery.com/category/manipulation/style-properties/"
title="View all posts filed under Style Properties"
src="null"
>Style Properties</a
>
</li>
</ul>
</li>
<li class="cat-item cat-item-39">
<a
href="http://api.jquery.com/category/miscellaneous/"
title="View all posts filed under Miscellaneous"
src="null"
>Miscellaneous</a
>
<ul class="children">
<li class="cat-item cat-item-40">
<a
href="http://api.jquery.com/category/miscellaneous/collection-manipulation/"
title="View all posts filed under Collection Manipulation"
src="null"
>Collection Manipulation</a
>
</li>
<li class="cat-item cat-item-41">
<a
href="http://api.jquery.com/category/miscellaneous/data-storage/"
title="View all posts filed under Data Storage"
src="null"
>Data Storage</a
>
</li>
<li class="cat-item cat-item-42">
<a
href="http://api.jquery.com/category/miscellaneous/dom-element-methods/"
title="View all posts filed under DOM Element Methods"
src="null"
>DOM Element Methods</a
>
</li>
<li class="cat-item cat-item-43">
<a
href="http://api.jquery.com/category/miscellaneous/setup-methods/"
title="View all posts filed under Setup Methods"
src="null"
>Setup Methods</a
>
</li>
</ul>
</li>
<li class="cat-item cat-item-44">
<a
href="http://api.jquery.com/category/offset/"
title="View all posts filed under Offset"
src="null"
>Offset</a
>
</li>
<li class="cat-item cat-item-45">
<a
href="http://api.jquery.com/category/properties/"
title="View all posts filed under Properties"
src="null"
>Properties</a
>
<ul class="children">
<li class="cat-item cat-item-46">
<a
href="http://api.jquery.com/category/properties/jquery-object-instance-properties/"
title="View all posts filed under Properties of jQuery Object Instances"
src="null"
>Properties of jQuery Object Instances</a
>
</li>
<li class="cat-item cat-item-47">
<a
href="http://api.jquery.com/category/properties/global-jquery-object-properties/"
title="View all posts filed under Properties of the Global jQuery Object"
src="null"
>Properties of the Global jQuery Object</a
>
</li>
</ul>
</li>
<li class="cat-item cat-item-92">
<a
href="http://api.jquery.com/category/removed/"
title="View all posts filed under Removed"
src="null"
>Removed</a
>
</li>
<li class="cat-item cat-item-48">
<a
href="http://api.jquery.com/category/selectors/"
title="View all posts filed under Selectors"
src="null"
>Selectors</a
>
<ul class="children">
<li class="cat-item cat-item-49">
<a
href="http://api.jquery.com/category/selectors/attribute-selectors/"
title="View all posts filed under Attribute"
src="null"
>Attribute</a
>
</li>
<li class="cat-item cat-item-50">
<a
href="http://api.jquery.com/category/selectors/basic-css-selectors/"
title="View all posts filed under Basic"
src="null"
>Basic</a
>
</li>
<li class="cat-item cat-item-51">
<a
href="http://api.jquery.com/category/selectors/basic-filter-selectors/"
title="View all posts filed under Basic Filter"
src="null"
>Basic Filter</a
>
</li>
<li class="cat-item cat-item-52">
<a
href="http://api.jquery.com/category/selectors/child-filter-selectors/"
title="View all posts filed under Child Filter"
src="null"
>Child Filter</a
>
</li>
<li class="cat-item cat-item-53">
<a
href="http://api.jquery.com/category/selectors/content-filter-selector/"
title="View all posts filed under Content Filter"
src="null"
>Content Filter</a
>
</li>
<li class="cat-item cat-item-54">
<a
href="http://api.jquery.com/category/selectors/form-selectors/"
title="View all posts filed under Form"
src="null"
>Form</a
>
</li>
<li class="cat-item cat-item-55">
<a
href="http://api.jquery.com/category/selectors/hierarchy-selectors/"
title="View all posts filed under Hierarchy"
src="null"
>Hierarchy</a
>
</li>
<li class="cat-item cat-item-56">
<a
href="http://api.jquery.com/category/selectors/jquery-selector-extensions/"
title="View all posts filed under jQuery Extensions"
src="null"
>jQuery Extensions</a
>
</li>
<li class="cat-item cat-item-57">
<a
href="http://api.jquery.com/category/selectors/visibility-filter-selectors/"
title="View all posts filed under Visibility Filter"
src="null"
>Visibility Filter</a
>
</li>
</ul>
</li>
<li class="cat-item cat-item-58">
<a
href="http://api.jquery.com/category/traversing/"
title="View all posts filed under Traversing"
src="null"
>Traversing</a
>
<ul class="children">
<li class="cat-item cat-item-59">
<a
href="http://api.jquery.com/category/traversing/filtering/"
title="View all posts filed under Filtering"
src="null"
>Filtering</a
>
</li>
<li class="cat-item cat-item-60">
<a
href="http://api.jquery.com/category/traversing/miscellaneous-traversal/"
title="View all posts filed under Miscellaneous Traversing"
src="null"
>Miscellaneous Traversing</a
>
</li>
<li class="cat-item cat-item-61">
<a
href="http://api.jquery.com/category/traversing/tree-traversal/"
title="View all posts filed under Tree Traversal"
src="null"
>Tree Traversal</a
>
</li>
</ul>
</li>
<li class="cat-item cat-item-63">
<a
href="http://api.jquery.com/category/utilities/"
title="View all posts filed under Utilities"
src="null"
>Utilities</a
>
</li>
<li class="cat-item cat-item-64">
<a
href="http://api.jquery.com/category/version/"
title="View all posts filed under Version"
src="null"
>Version</a
>
<ul class="children">
<li class="cat-item cat-item-65">
<a
href="http://api.jquery.com/category/version/1.0/"
title="View all posts filed under Version 1.0"
src="null"
>Version 1.0</a
>
</li>
<li class="cat-item cat-item-66">
<a
href="http://api.jquery.com/category/version/1.0.4/"
title="View all posts filed under Version 1.0.4"
src="null"
>Version 1.0.4</a
>
</li>
<li class="cat-item cat-item-67">
<a
href="http://api.jquery.com/category/version/1.1/"
title="View all posts filed under Version 1.1"
src="null"
>Version 1.1</a
>
</li>
<li class="cat-item cat-item-68">
<a
href="http://api.jquery.com/category/version/1.1.2/"
title="View all posts filed under Version 1.1.2"
src="null"
>Version 1.1.2</a
>
</li>
<li class="cat-item cat-item-69">
<a
href="http://api.jquery.com/category/version/1.1.3/"
title="View all posts filed under Version 1.1.3"
src="null"
>Version 1.1.3</a
>
</li>
<li class="cat-item cat-item-70">
<a
href="http://api.jquery.com/category/version/1.1.4/"
title="View all posts filed under Version 1.1.4"
src="null"
>Version 1.1.4</a
>
</li>
<li class="cat-item cat-item-71">
<a
href="http://api.jquery.com/category/version/1.2/"
title="View all posts filed under Version 1.2"
src="null"
>Version 1.2</a
>
</li>
<li class="cat-item cat-item-72">
<a
href="http://api.jquery.com/category/version/1.2.3/"
title="View all posts filed under Version 1.2.3"
src="null"
>Version 1.2.3</a
>
</li>
<li class="cat-item cat-item-73">
<a
href="http://api.jquery.com/category/version/1.2.6/"
title="View all posts filed under Version 1.2.6"
src="null"
>Version 1.2.6</a
>
</li>
<li class="cat-item cat-item-74">
<a
href="http://api.jquery.com/category/version/1.3/"
title="View all posts filed under Version 1.3"
src="null"
>Version 1.3</a
>
</li>
<li class="cat-item cat-item-75">
<a
href="http://api.jquery.com/category/version/1.4/"
title="View all posts filed under Version 1.4"
src="null"
>Version 1.4</a
>
</li>
<li class="cat-item cat-item-76">
<a
href="http://api.jquery.com/category/version/1.4.1/"
title="View all posts filed under Version 1.4.1"
src="null"
>Version 1.4.1</a
>
</li>
<li class="cat-item cat-item-77">
<a
href="http://api.jquery.com/category/version/1.4.2/"
title="View all posts filed under Version 1.4.2"
src="null"
>Version 1.4.2</a
>
</li>
<li class="cat-item cat-item-78">
<a
href="http://api.jquery.com/category/version/1.4.3/"
title="View all posts filed under Version 1.4.3"
src="null"
>Version 1.4.3</a
>
</li>
<li class="cat-item cat-item-79">
<a
href="http://api.jquery.com/category/version/1.4.4/"
title="View all posts filed under Version 1.4.4"
src="null"
>Version 1.4.4</a
>
</li>
<li class="cat-item cat-item-80">
<a
href="http://api.jquery.com/category/version/1.5/"
title="View all posts filed under Version 1.5"
src="null"
>Version 1.5</a
>
</li>
<li class="cat-item cat-item-81">
<a
href="http://api.jquery.com/category/version/1.5.1/"
title="View all posts filed under Version 1.5.1"
src="null"
>Version 1.5.1</a
>
</li>
<li class="cat-item cat-item-82">
<a
href="http://api.jquery.com/category/version/1.6/"
title="View all posts filed under Version 1.6"
src="null"
>Version 1.6</a
>
</li>
<li class="cat-item cat-item-83">
<a
href="http://api.jquery.com/category/version/1.7/"
title="View all posts filed under Version 1.7"
src="null"
>Version 1.7</a
>
</li>
<li class="cat-item cat-item-84">
<a
href="http://api.jquery.com/category/version/1.8/"
title="View all posts filed under Version 1.8"
src="null"
>Version 1.8</a
>
</li>
<li class="cat-item cat-item-86">
<a
href="http://api.jquery.com/category/version/1.9/"
title="View all posts filed under Version 1.9"
src="null"
>Version 1.9</a
>
</li>
</ul>
</li>
</ul>
</aside>
</div>
</div>
</div>
</div>
<footer class="clearfix simple">
<div class="constrain">
<div class="row">
<div class="eight columns">
<h3><span>Quick Access</span></h3>
<div class="cdn">
<strong>CDN</strong>
<input
value="//code.jquery.com/jquery-1.10.2.min.js"
readonly=""
/>
</div>
<div class="download">
<strong
><a href="http://jquery.com/download/" src="null"
>Download jQuery 1.10.2 →</a
></strong
>
</div>
<div class="tinynav-container">
<h3><span>More jQuery Sites</span></h3>
<select id="tinynav1" class="tinynav tinynav1"
><option>Browse...</option
><option value="http://plugins.jquery.com/">Plugins</option
><option value="http://contribute.jquery.org/"
>Contribute</option
><option value="http://contribute.jquery.org/cla/">- CLA</option
><option value="http://contribute.jquery.org/style-guide/"
>- Style Guides</option
><option value="http://contribute.jquery.org/triage/"
>- Bug Triage</option
><option value="http://contribute.jquery.org/code/"
>- Code</option
><option value="http://contribute.jquery.org/documentation/"
>- Documentation</option
><option value="http://contribute.jquery.org/web-sites/"
>- Web Sites</option
><option value="http://events.jquery.org/">Events</option
><option
value="http://www.deque.com/deque-partners-jquery-create-accessibility-summit"
>- Oct 10-11 | jQuery Accessibility Summit</option
><option value="http://jquery.itmozg.ru/"
>- Oct 15 | jQuery Russia</option
><option
value="http://modernweb.com/training/jquery-oct-2013.php"
>- Oct 15-17 | jQuery Virtual Training</option
><option value="http://2013.cssdevconf.com/"
>- Oct 21-22 | CSS Dev Conf</option
><option value="http://javascriptsummit.com/"
>- Nov 19-21 | JavaScript Summit</option
><option value="http://events.jquery.org/2014/san-diego/"
>- Feb 12-13 | jQuery San Diego</option
><option value="http://www.gentics.com/jquery-europe"
>- Feb 28-Mar 1 | jQuery Europe</option
><option value="http://jqueryuk.com"
>- May 16 | jQuery UK</option
><option value="https://jquery.org/support/">Support</option
><option value="http://learn.jquery.com/"
>- Learning Center</option
><option value="http://try.jquery.com/">- Try jQuery</option
><option value="http://irc.jquery.org/">- IRC/Chat</option
><option value="http://forum.jquery.com/">- Forums</option
><option value="http://stackoverflow.com/tags/jquery/info"
>- Stack Overflow</option
><option value="https://jquery.org/support/"
>- Commercial Support</option
><option value="https://jquery.org/">jQuery Foundation</option
><option value="https://jquery.org/join/">- Join</option
><option value="https://jquery.org/members/">- Members</option
><option value="https://jquery.org/team/">- Team</option
><option value="http://brand.jquery.org/">- Brand Guide</option
><option value="https://jquery.org/donate/"
>- Donate</option
></select
>
</div>
<ul class="footer-icon-links">
<li>
<a
class="icon-github"
href="http://github.com/jquery/jquery"
src="null"
>GitHub <small>jQuery <br />Source</small></a
>
</li>
<li>
<a class="icon-group" href="http://forum.jquery.com" src="null"
>Forum <small>Community <br />Support</small></a
>
</li>
<li>
<a
class="icon-warning-sign"
href="http://bugs.jquery.com"
src="null"
>Bugs <small>Issue <br />Tracker</small></a
>
</li>
</ul>
</div>
<div class="four columns">
<h3><span>Books</span></h3>
<ul class="books">
<li>
<a
href="http://www.packtpub.com/learning-jquery-with-simple-javascript-techniques-fourth-edition/book"
src="null"
>
<span class="bottom"
><img
src="null"
alt="Learning jQuery 4th Edition by Karl Swedberg and Jonathan Chaffer"
width="92"
height="114"
/></span>
<strong>Learning jQuery Fourth Edition</strong><br />
<cite>Karl Swedberg and Jonathan Chaffer</cite>
</a>
</li>
<li>
<a
href="http://www.manning.com/affiliate/idevaffiliate.php?id=648_176"
src="null"
>
<span
><img
src="null"
alt="jQuery in Action by Bear Bibeault and Yehuda Katz"
width="92"
height="114"
/></span>
<strong>jQuery in Action</strong><br />
<cite>Bear Bibeault and Yehuda Katz</cite>
</a>
</li>
<li>
<a
href="http://www.syncfusion.com/resources/techportal/ebooks/jquery?utm_medium=BizDev-jQuery.org0513"
src="null"
>
<span
><img
src="null"
alt="jQuery Succinctly by Cody Lindley"
width="92"
height="114"
/></span>
<strong>jQuery Succinctly</strong><br />
<cite>Cody Lindley</cite>
</a>
</li>
</ul>
</div>
</div>
<div id="legal">
<ul class="footer-site-links">
<li>
<a class="icon-pencil" href="http://learn.jquery.com/" src="null"
>Learning Center</a
>
</li>
<li>
<a class="icon-group" href="http://forum.jquery.com/" src="null"
>Forum</a
>
</li>
<li>
<a class="icon-wrench" href="http://api.jquery.com/" src="null"
>API</a
>
</li>
<li>
<a
class="icon-twitter"
href="http://twitter.com/jquery"
src="null"
>Twitter</a
>
</li>
<li>
<a class="icon-comments" href="http://irc.jquery.org/" src="null"
>IRC</a
>
</li>
</ul>
<p class="copyright">
Copyright 2013
<a href="https://jquery.org/team/" src="null"
>The jQuery Foundation</a
>.<br />
<span class="sponsor-line"
><a
href="http://mediatemple.net"
rel="noindex,nofollow"
class="mt-link"
src="null"
>Web hosting by Media Temple</a
>
|
<a
href="http://www.maxcdn.com"
rel="noindex,nofollow"
class="mc-link"
src="null"
>CDN by MaxCDN</a
>
|
<a href="http://wordpress.org/" class="wp-link" src="null"
>Powered by WordPress</a
>
| Thanks:
<a href="https://jquery.org/members/" src="null">Members</a>,
<a href="https://jquery.org/sponsors/" src="null"
>Sponsors</a
></span
>
</p>
</div>
</div>
</footer>
<script>
// biome-ignore lint/correctness/noInvalidUseBeforeDeclaration: Vendor script
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1076265-1']);
_gaq.push(['_setDomainName', 'api.jquery.com']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(() => {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src =
`${document.location.protocol === 'https:'
? 'https://ssl'
: 'http://www'}.google-analytics.com/ga.js`;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="cboxOverlay" style="display: none;"></div>
<div id="colorbox" class="" style="display: none;">
<div id="cboxWrapper">
<div>
<div id="cboxTopLeft" style="float: left;"></div>
<div id="cboxTopCenter" style="float: left;"></div>
<div id="cboxTopRight" style="float: left;"></div>
</div>
<div style="clear: left;">
<div id="cboxMiddleLeft" style="float: left;"></div>
<div id="cboxContent" style="float: left;">
<div
id="cboxLoadedContent"
style="width: 0px; height: 0px; overflow: hidden; float: left;"
></div>
<div id="cboxTitle" style="float: left;"></div>
<div id="cboxCurrent" style="float: left;"></div>
<div id="cboxNext" style="float: left;"></div>
<div id="cboxPrevious" style="float: left;"></div>
<div id="cboxSlideshow" style="float: left;"></div>
<div id="cboxClose" style="float: left;"></div>
</div>
<div id="cboxMiddleRight" style="float: left;"></div>
</div>
<div style="clear: left;">
<div id="cboxBottomLeft" style="float: left;"></div>
<div id="cboxBottomCenter" style="float: left;"></div>
<div id="cboxBottomRight" style="float: left;"></div>
</div>
</div>
<div
style="
position: absolute;
width: 9999px;
visibility: hidden;
display: none;
"
></div>
</div>
</body>
</html>
================================================
FILE: biome.json
================================================
{
"$schema": "https://biomejs.dev/schemas/2.4.6/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true
},
"files": {
"ignoreUnknown": true
},
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 2
},
"javascript": {
"formatter": {
"quoteStyle": "single"
}
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"complexity": {
"useLiteralKeys": "off",
"noArguments": "off",
"noCommaOperator": "off",
"noUselessStringConcat": "error",
"noUselessUndefined": "error",
"useSimplifiedLogicExpression": "error",
"useWhile": "error"
},
"style": {
"noNonNullAssertion": "off",
"noInferrableTypes": "error",
"noNegationElse": "error",
"noUnusedTemplateLiteral": "error",
"noUselessElse": "error",
"noYodaExpression": "error",
"useAsConstAssertion": "error",
"useCollapsedElseIf": "error",
"useCollapsedIf": "error",
"useConsistentArrayType": "error",
"useConsistentArrowReturn": "error",
"useConsistentMemberAccessibility": "error",
"useConsistentObjectDefinitions": "error",
"useConsistentTypeDefinitions": "error",
"useDefaultParameterLast": "error",
"useExplicitLengthCheck": "error",
"useFilenamingConvention": "error",
"useNumberNamespace": "error",
"useNumericSeparators": "error",
"useObjectSpread": "error",
"useShorthandAssign": "error",
"useUnifiedTypeSignatures": "error"
},
"suspicious": {
"noAssignInExpressions": "off",
"noConfusingVoidType": "off",
"noConstEnum": "off",
"noExplicitAny": "off",
"noImplicitAnyLet": "off",
"noShadowRestrictedNames": "off",
"noUnsafeDeclarationMerging": "off",
"noConstantBinaryExpressions": "error",
"useAwait": "error"
},
"performance": {
"useTopLevelRegex": "error"
}
}
},
"css": {
"parser": {
"tailwindDirectives": true
}
},
"assist": {
"enabled": true,
"actions": {
"source": {
"organizeImports": "on"
}
}
},
"overrides": [
{
"includes": ["**/*.{test,spec}.ts", "test/**/*.ts"],
"javascript": {
"globals": [
"jest",
"describe",
"it",
"beforeEach",
"afterEach",
"expect",
"vi"
]
}
},
{
"includes": ["**/*.astro"],
"linter": {
"rules": {
"correctness": {
"noUnusedImports": "off",
"noUnusedVariables": "off"
},
"style": {
"useFilenamingConvention": "off"
},
"performance": {
"useTopLevelRegex": "off"
}
}
}
}
]
}
================================================
FILE: eslint.config.js
================================================
import { fileURLToPath } from 'node:url'; // Added for .gitignore path
import { includeIgnoreFile } from '@eslint/compat'; // Added for .gitignore
import feedicFlatConfig from '@feedic/eslint-config';
import { commonTypeScriptRules } from '@feedic/eslint-config/typescript';
import eslintPluginVitest from '@vitest/eslint-plugin';
import { defineConfig } from 'eslint/config';
import eslintConfigBiome from 'eslint-config-biome';
import globals from 'globals';
import tseslint from 'typescript-eslint';
const gitignorePath = fileURLToPath(new URL('.gitignore', import.meta.url));
export default defineConfig(
includeIgnoreFile(gitignorePath), // Handle .gitignore patterns
// Global linter options
{
linterOptions: {
reportUnusedDisableDirectives: 'error',
},
},
// Base configurations for all relevant files
...feedicFlatConfig,
{
rules: {
'jsdoc/tag-lines': [2, 'any', { startLines: 1 }],
'jsdoc/require-param-type': 0,
'jsdoc/require-returns-type': 0,
'jsdoc/no-types': 2,
'jsdoc/require-returns-check': 0,
'jsdoc/check-tag-names': [
2,
{
definedTags: ['private'],
},
],
},
},
// Global custom rules and language options
{
languageOptions: {
globals: globals.node,
parserOptions: {
projectService: {
allowDefaultProject: ['*.js'],
defaultProject: 'tsconfig.json',
},
tsconfigRootDir: import.meta.dirname, // eslint-disable-line n/no-unsupported-features/node-builtins
},
},
rules: {
'n/file-extension-in-import': [2, 'always'],
'no-lonely-if': 2,
'no-proto': 2,
'no-else-return': [2, { allowElseIf: false }],
'no-unused-expressions': 2,
'no-useless-call': 2,
'no-constant-binary-expression': 2,
'no-void': 2,
'unicorn/no-array-callback-reference': 0,
'unicorn/no-array-reduce': 0,
'unicorn/no-for-loop': 0,
'unicorn/no-useless-undefined': 0,
'unicorn/prefer-array-find': 0,
'unicorn/prevent-abbreviations': 0,
},
},
// TypeScript specific configurations
{
// Custom overrides and settings for TypeScript files
files: ['**/*.{c,m,}ts', '**/*.tsx'], // Ensure this block specifically targets TS files
extends: [
...tseslint.configs.recommendedTypeChecked,
...tseslint.configs.stylisticTypeChecked,
],
languageOptions: {
parser: tseslint.parser,
},
rules: {
...commonTypeScriptRules,
// Enabling this in cheerio currently triggers broad churn across src + website.
'@typescript-eslint/no-unnecessary-condition': 0,
},
},
// Vitest specific configuration (for *.spec.ts files)
{
files: ['**/*.spec.ts'],
plugins: { vitest: eslintPluginVitest },
languageOptions: {
globals: globals.vitest, // Add Vitest globals
},
rules: {
// Assuming "recommended" is the flat config equivalent for "legacy-recommended"
...eslintPluginVitest.configs.recommended.rules,
'n/no-unpublished-import': 0, // Allow importing devDependencies
},
},
// Website specific configuration
{
files: ['website/**/*.{m,}ts{x,}'],
languageOptions: {
parserOptions: {
projectService: {
allowDefaultProject: ['*.mjs'],
},
tsconfigRootDir: `${import.meta.dirname}/website`, // eslint-disable-line n/no-unsupported-features/node-builtins
},
},
},
// Prettier - must be the last configuration to override styling rules
eslintConfigBiome,
);
================================================
FILE: package.json
================================================
{
"name": "cheerio",
"version": "1.2.0",
"description": "The fast, flexible & elegant library for parsing and manipulating HTML and XML.",
"keywords": [
"htmlparser",
"jquery",
"selector",
"scraper",
"parser",
"dom",
"xml",
"html"
],
"homepage": "https://cheerio.js.org/",
"bugs": {
"url": "https://github.com/cheeriojs/cheerio/issues"
},
"repository": {
"type": "git",
"url": "git://github.com/cheeriojs/cheerio.git"
},
"funding": "https://github.com/cheeriojs/cheerio?sponsor=1",
"license": "MIT",
"author": "Matt Mueller <mattmuelle@gmail.com>",
"sideEffects": false,
"maintainers": [
"Felix Boehm <me@feedic.com>"
],
"type": "module",
"exports": {
".": {
"browser": {
"types": "./dist/browser/index.d.ts",
"default": "./dist/browser/index.js"
},
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/commonjs/index.d.ts",
"default": "./dist/commonjs/index.js"
}
},
"./package.json": "./package.json",
"./slim": {
"browser": {
"types": "./dist/browser/slim.d.ts",
"default": "./dist/browser/slim.js"
},
"import": {
"types": "./dist/esm/slim.d.ts",
"default": "./dist/esm/slim.js"
},
"require": {
"types": "./dist/commonjs/slim.d.ts",
"default": "./dist/commonjs/slim.js"
}
},
"./utils": {
"browser": {
"types": "./dist/browser/utils.d.ts",
"default": "./dist/browser/utils.js"
},
"import": {
"types": "./dist/esm/utils.d.ts",
"default": "./dist/esm/utils.js"
},
"require": {
"types": "./dist/commonjs/utils.d.ts",
"default": "./dist/commonjs/utils.js"
}
}
},
"main": "./dist/commonjs/index.js",
"module": "./dist/esm/index.js",
"browser": "./dist/browser/index.js",
"types": "./dist/commonjs/index.d.ts",
"files": [
"dist",
"src",
"!**/*.spec.{t,j}s",
"!**/__tests__/*",
"!**/__fixtures__/*"
],
"scripts": {
"benchmark": "node --import=tsx benchmark/benchmark.ts",
"build": "tshy",
"format": "npm run format:es && npm run format:biome",
"format:biome": "biome check --write .",
"format:es": "npm run lint:es -- --fix",
"lint": "npm run lint:es && npm run lint:ts && npm run lint:biome",
"lint:biome": "biome check .",
"lint:es": "eslint .",
"lint:ts": "tsc --noEmit",
"prepare": "husky",
"prepublishOnly": "npm run build",
"test": "npm run lint && npm run test:vi",
"test:vi": "vitest run",
"update-sponsors": "tsx scripts/fetch-sponsors.mts"
},
"lint-staged": {
"*.js": [
"biome check --write",
"eslint --fix"
],
"*.{json,md,ts}": [
"biome check --write"
]
},
"dependencies": {
"cheerio-select": "^2.1.0",
"dom-serializer": "^2.0.0",
"domhandler": "^5.0.3",
"domutils": "^3.2.2",
"encoding-sniffer": "^0.2.1",
"htmlparser2": "^10.1.0",
"parse5": "^7.3.0",
"parse5-htmlparser2-tree-adapter": "^7.1.0",
"parse5-parser-stream": "^7.1.2",
"undici": "^7.24.4",
"whatwg-mimetype": "^4.0.0"
},
"devDependencies": {
"@biomejs/biome": "^2.4.4",
"@eslint/compat": "^2.0.3",
"@feedic/eslint-config": "^0.3.1",
"@imgix/js-core": "^3.8.0",
"@octokit/graphql": "^9.0.3",
"@types/jsdom": "^28.0.0",
"@types/node": "^25.5.0",
"@types/whatwg-mimetype": "^3.0.2",
"@vitest/coverage-v8": "^4.1.0",
"@vitest/eslint-plugin": "^1.6.12",
"eslint": "^10.0.3",
"eslint-config-biome": "^2.1.3",
"globals": "^17.4.0",
"husky": "^9.1.7",
"jquery": "^4.0.0",
"jsdom": "^29.0.0",
"lint-staged": "^16.4.0",
"prettier-plugin-jsdoc": "^1.8.0",
"tinybench": "^6.0.0",
"tshy": "^3.3.2",
"tsx": "^4.21.0",
"typescript": "^5.9.3",
"typescript-eslint": "^8.57.1",
"vitest": "^4.0.18"
},
"engines": {
"node": ">=20.18.1"
},
"tshy": {
"esmDialects": [
"browser"
],
"exports": {
".": "./src/index.ts",
"./slim": "./src/slim.ts",
"./utils": "./src/utils.ts",
"./package.json": "./package.json"
},
"exclude": [
"**/*.spec.ts",
"**/__fixtures__/*",
"**/__tests__/*"
]
}
}
================================================
FILE: scripts/fetch-sponsors.mts
================================================
/**
* @file Script To fetch sponsor data from Open Collective and GitHub.
*
* Adapted from
* https://github.com/eslint/website/blob/230e73457dcdc2353ad7934e876a5a222a17b1d7/_tools/fetch-sponsors.js.
*/
/* eslint-disable @typescript-eslint/no-unsafe-assignment,
@typescript-eslint/no-unsafe-return,
@typescript-eslint/no-unsafe-call,
@typescript-eslint/no-unsafe-argument,
@typescript-eslint/no-unsafe-member-access,
@typescript-eslint/prefer-nullish-coalescing */
import * as fs from 'node:fs/promises';
import ImgixClient from '@imgix/js-core';
import { graphql as githubGraphQL } from '@octokit/graphql';
import { request } from 'undici';
type Tier = 'headliner' | 'sponsor' | 'professional' | 'backer';
interface Sponsor {
createdAt: string;
name: string;
image: string;
url: string;
type: 'ORGANIZATION' | 'INDIVIDUAL' | 'FUND';
monthlyDonation: number;
totalDonations: number;
source: 'github' | 'opencollective' | 'manual';
tier: Tier | null;
}
const tierSponsors: Record<Tier, Sponsor[]> = {
headliner: [
// Some sponsors are manually added here.
{
createdAt: '2022-06-24',
name: 'Github',
image: 'https://github.com/github.png',
url: 'https://github.com/',
type: 'ORGANIZATION',
monthlyDonation: 0,
totalDonations: 0,
source: 'manual',
tier: 'headliner',
},
{
createdAt: '2018-05-02',
name: 'AirBnB',
image: 'https://github.com/airbnb.png',
url: 'https://www.airbnb.com/',
type: 'ORGANIZATION',
monthlyDonation: 0,
totalDonations: 0,
source: 'manual',
tier: 'headliner',
},
{
createdAt: '2026-01-21',
name: 'HasData',
image: 'https://hasdata.com/favicon.svg',
url: 'https://hasdata.com',
type: 'ORGANIZATION',
monthlyDonation: 0,
totalDonations: 0,
source: 'manual',
tier: 'headliner',
},
{
createdAt: '2026-01-28',
name: 'brand.dev',
image: 'https://github.com/brand-dot-dev.png',
url: 'https://brand.dev/',
type: 'ORGANIZATION',
monthlyDonation: 0,
totalDonations: 0,
source: 'manual',
tier: 'headliner',
},
],
sponsor: [],
professional: [],
backer: [],
};
const { CHEERIO_SPONSORS_GITHUB_TOKEN, IMGIX_TOKEN } = process.env;
if (!CHEERIO_SPONSORS_GITHUB_TOKEN) {
throw new Error('Missing CHEERIO_SPONSORS_GITHUB_TOKEN.');
}
// @ts-expect-error - Types don't have a constructor
const imgix = new ImgixClient({
domain: 'humble.imgix.net',
secureURLToken: IMGIX_TOKEN,
});
/**
* Returns the tier ID for a given donation amount.
*
* @param monthlyDonation - The monthly donation in dollars.
* @returns The ID of the tier the donation belongs to.
*/
function getTierSlug(monthlyDonation: number): Tier | null {
if (monthlyDonation >= 250) {
return 'headliner';
}
if (monthlyDonation >= 100) {
return 'sponsor';
}
if (monthlyDonation >= 25) {
return 'professional';
}
if (monthlyDonation >= 5) {
return 'backer';
}
return null;
}
/**
* Fetch order data from Open Collective using the GraphQL API.
*
* @returns An array of sponsors.
*/
async function fetchOpenCollectiveSponsors(): Promise<Sponsor[]> {
const endpoint = 'https://api.opencollective.com/graphql/v2';
const query = `{
account(slug: "cheerio") {
orders(status: ACTIVE, filter: INCOMING) {
nodes {
createdAt
fromAccount {
name
website
imageUrl
type
}
amount {
value
}
tier {
slug
}
frequency
totalDonations {
value
}
}
}
}
}`;
const { body } = await request(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query }),
});
const payload: any = await body.json();
return payload.data.account.orders.nodes.map((order: any): Sponsor => {
const donation = order.amount.value * 100;
const monthlyDonation =
order.frequency === 'YEARLY' ? Math.round(donation / 12) : donation;
return {
createdAt: order.createdAt,
name: order.fromAccount.name,
url: order.fromAccount.website,
image: order.fromAccount.imageUrl,
type: order.fromAccount.type,
monthlyDonation,
totalDonations: order.totalDonations.value * 100,
source: 'opencollective',
tier: getTierSlug(monthlyDonation / 100),
};
});
}
function getMonthsActive(date: string): number {
const now = new Date();
const then = new Date(date);
const months = (now.getFullYear() - then.getFullYear()) * 12;
return months - then.getMonth() + now.getMonth() + 1;
}
/**
* Fetches GitHub Sponsors data using the GraphQL API.
*
* @returns An array of sponsors.
*/
async function fetchGitHubSponsors(): Promise<Sponsor[]> {
const { organization } = await githubGraphQL<any>(
`{
organization(login: "cheeriojs") {
sponsorshipsAsMaintainer(first: 100) {
nodes {
sponsor: sponsorEntity {
... on User {
name
login
avatarUrl
url
websiteUrl
isViewer
}
... on Organization {
name
login
avatarUrl
url
websiteUrl
viewerCanAdminister
}
}
tier {
monthlyPriceInDollars
}
createdAt
}
}
}
}
`,
{
headers: {
authorization: `token ${CHEERIO_SPONSORS_GITHUB_TOKEN}`,
},
},
);
// Return an array in the same format as Open Collective
return organization.sponsorshipsAsMaintainer.nodes.map(
({ sponsor, tier, createdAt }: any): Sponsor => ({
createdAt,
name: sponsor.name,
image: `${sponsor.avatarUrl}&s=128`,
url: sponsor.websiteUrl || sponsor.url,
type:
// Workaround to get the type — fetch a field that only exists on users.
sponsor.isViewer === undefined ? 'ORGANIZATION' : 'INDIVIDUAL',
monthlyDonation: (tier?.monthlyPriceInDollars ?? 0) * 100,
totalDonations:
getMonthsActive(createdAt) * tier?.monthlyPriceInDollars * 100,
source: 'github',
tier: getTierSlug(tier?.monthlyPriceInDollars ?? 0),
}),
);
}
async function fetchSponsors(): Promise<Sponsor[]> {
const results = await Promise.all([
fetchOpenCollectiveSponsors(),
fetchGitHubSponsors(),
]);
return results.flat();
}
/*
* Remove sponsors from lower tiers that have individual accounts,
* but are clearly orgs.
*/
const MISLABELED_ORGS =
/[ck]as[iy]+no|bet$|poker|gambling|coffee|tuxedo|(?:ph|f)oto/i;
const README_PATH = new URL('../Readme.md', import.meta.url);
const JSON_PATH = new URL('../website/sponsors.json', import.meta.url);
const SECTION_START_BEGINNING = '<!-- BEGIN SPONSORS:';
const SECTION_START_END = '-->';
const SECTION_END = '<!-- END SPONSORS -->';
const professionalToBackerOverrides = new Map([
['Vasy Kafidoff', 'https://kafidoff.com'],
]);
const sponsors = await fetchSponsors();
console.log('Received sponsors:', sponsors);
// Remove sponsors that are already in the pre-populated headliners
for (let i = 0; i < sponsors.length; i++) {
if (
tierSponsors.headliner.some((sponsor) => sponsor.url === sponsors[i].url)
) {
sponsors.splice(i, 1);
i--;
}
}
sponsors.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
// Process into a useful format
for (const sponsor of sponsors) {
if (
!sponsor.tier || // Always skip if sponsor has no tier (e.g., donation < $5)
// OR if it's a 'professional' or 'backer' tier AND meets specific filtering criteria
((sponsor.tier === 'professional' || sponsor.tier === 'backer') &&
(sponsor.type === 'ORGANIZATION' ||
MISLABELED_ORGS.test(sponsor.name) ||
MISLABELED_ORGS.test(sponsor.url)))
) {
continue;
}
if (
(sponsor.tier === 'professional' || sponsor.tier === 'backer') &&
professionalToBackerOverrides.has(sponsor.name)
) {
sponsor.url = professionalToBackerOverrides.get(sponsor.name)!;
}
tierSponsors[sponsor.tier].push(sponsor);
}
for (const tier of Object.values(tierSponsors)) {
// Sort order based on total donations
tier.sort((a: Sponsor, b: Sponsor) => b.totalDonations - a.totalDonations);
// Set all donations to 0 before writing to JSON
for (const sponsor of tier) {
sponsor.monthlyDonation = 0;
sponsor.totalDonations = 0;
}
}
// Write sponsors.json
await fs.writeFile(JSON_PATH, JSON.stringify(tierSponsors, null, 2), 'utf8');
// Prepend professionals to backers for now
tierSponsors.backer.unshift(...tierSponsors.professional);
let readme = await fs.readFile(README_PATH, 'utf8');
const TIER_IMAGE_SIZES: Record<Tier, number> = {
headliner: 128,
sponsor: 64,
professional: 64,
backer: 48,
};
for (let sectionStartIndex = 0; ; ) {
sectionStartIndex = readme.indexOf(
SECTION_START_BEGINNING,
sectionStartIndex,
);
if (sectionStartIndex < 0) break;
sectionStartIndex += SECTION_START_BEGINNING.length;
const sectionStartEndIndex = readme.indexOf(
SECTION_START_END,
sectionStartIndex,
);
const sectionName = readme
.slice(sectionStartIndex, sectionStartEndIndex)
.trim() as Tier;
const sectionContentStart = sectionStartEndIndex + SECTION_START_END.length;
const sectionEndIndex = readme.indexOf(SECTION_END, sectionContentStart);
readme = `${readme.slice(0, sectionContentStart)}\n\n${tierSponsors[
sectionName
]
.map((s: Sponsor) => {
const size = TIER_IMAGE_SIZES[s.tier ?? sectionName];
// Display each sponsor's image in the README.
return `<a href="${s.url}" target="_blank" rel="noopener noreferrer">
<img height="${size}px" width="${size}px" src="${imgix.buildURL(
s.image,
{
w: size,
h: size,
fit: 'fillmax',
fill: 'solid',
},
)}" title="${s.name}" alt="${s.name}"></img>
</a>`;
})
.join('\n')}\n\n${readme.slice(sectionEndIndex)}`;
}
await fs.writeFile(README_PATH, readme, {
encoding: 'utf8',
});
================================================
FILE: src/__fixtures__/fixtures.ts
================================================
import type { CheerioAPI } from '../load.js';
import { load } from '../load-parse.js';
/** A Cheerio instance with no content. */
export const cheerio: CheerioAPI = load([]);
export const fruits: string = [
'<ul id="fruits">',
'<li class="apple">Apple</li>',
'<li class="orange">Orange</li>',
'<li class="pear">Pear</li>',
'</ul>',
].join('');
export const vegetables: string = [
'<ul id="vegetables">',
'<li class="carrot">Carrot</li>',
'<li class="sweetcorn">Sweetcorn</li>',
'</ul>',
].join('');
export const divcontainers: string = [
'<div class="container">',
'<div class="inner">First</div>',
'<div class="inner">Second</div>',
'</div>',
'<div class="container">',
'<div class="inner">Third</div>',
'<div class="inner">Fourth</div>',
'</div>',
'<div id="new"><div>',
'<div>\n\n<p><em><b></b></em></p>\n\n</div>',
'</div>',
].join('');
export const chocolates: string = [
'<ul id="chocolates">',
'<li class="linth" data-highlight="Lindor" data-origin="swiss">Linth</li>',
'<li class="frey" data-taste="sweet" data-best-collection="Mahony">Frey</li>',
'<li class="cailler">Cailler</li>',
'</ul>',
].join('');
export const drinks: string = [
'<ul id="drinks">',
'<li class="beer">Beer</li>',
'<li class="juice">Juice</li>',
'<li class="milk">Milk</li>',
'<li class="water">Water</li>',
'<li class="cider">Cider</li>',
'</ul>',
].join('');
export const food: string = [
'<ul id="food">',
fruits,
vegetables,
'</ul>',
].join('');
export const eleven = `
<html>
<body>
<ul>
<li>One</li>
<li>Two</li>
<li class="blue sel">Three</li>
<li class="red">Four</li>
</ul>
<ul>
<li class="red">Five</li>
<li>Six</li>
<li class="blue">Seven</li>
</ul>
<ul>
<li>Eight</li>
<li class="red sel">Nine</li>
<li>Ten</li>
<li class="sel">Eleven</li>
</ul>
</body>
</html>
`;
export const unwrapspans: string = [
'<div id=unwrap style="display: none;">',
'<div id=unwrap1><span class=unwrap>a</span><span class=unwrap>b</span></div>',
'<div id=unwrap2><span class=unwrap>c</span><span class=unwrap>d</span></div>',
'<div id=unwrap3><b><span class="unwrap unwrap3">e</span></b><b><span class="unwrap unwrap3">f</span></b></div>',
'</div>',
].join('');
export const inputs: string = [
'<button id="btn-value" value="button">Button</button>',
'<button id="btn-valueless">Button</button>',
'<select id="one"><option value="option_not_selected">Option not selected</option><option value="option_selected" selected>Option selected</option></select>',
'<select id="one-valueless"><option>Option not selected</option><option selected>Option selected</option></select>',
'<select id="one-html-entity"><option>Option not selected</option><option selected>Option <selected></option></select>',
'<select id="one-nested"><option>Option not selected</option><option selected>Option <span>selected</span></option></select>',
'<input type="text" value="input_text" />',
'<input type="checkbox" name="checkbox_off" value="off" /><input type="checkbox" name="checkbox_on" value="on" checked />',
'<input type="checkbox" name="checkbox_valueless" />',
'<input type="radio" value="off" name="radio" /><input type="radio" name="radio" value="on" checked />',
'<input type="radio" value="off" name="radio[brackets]" /><input type="radio" name="radio[brackets]" value="on" checked />',
'<input type="radio" name="radio_valueless" />',
'<select id="multi" multiple><option value="1">1</option><option value="2" selected>2</option><option value="3" selected>3</option><option value="4">4</option></select>',
'<select id="multi-valueless" multiple><option>1</option><option selected>2</option><option selected>3</option><option>4</option></select>',
].join('');
export const text: string = [
'<p>Apples, <b>oranges</b> and pears.</p>',
'<p>Carrots and <!-- sweetcorn --></p>',
].join('');
export const forms: string = [
'<form id="simple"><input type="text" name="fruit" value="Apple" /></form>',
'<form id="nested"><div><input type="text" name="fruit" value="Apple" /></div><input type="text" name="vegetable" value="Carrot" /></form>',
'<form id="disabled"><input type="text" name="fruit" value="Apple" disabled /></form>',
'<form id="submit"><input type="text" name="fruit" value="Apple" /><input type="submit" name="submit" value="Submit" /></form>',
'<form id="select"><select name="fruit"><option value="Apple">Apple</option><option value="Orange" selected>Orange</option></select></form>',
'<form id="unnamed"><input type="text" name="fruit" value="Apple" /><input type="text" value="Carrot" /></form>',
'<form id="multiple"><select name="fruit" multiple><option value="Apple" selected>Apple</option><option value="Orange" selected>Orange</option><option value="Carrot">Carrot</option></select></form>',
'<form id="textarea"><textarea name="fruits">Apple\nOrange</textarea></form>',
'<form id="spaces"><input type="text" name="fruit" value="Blood orange" /></form>',
].join('');
export const noscript: string = [
'</body>',
'<noscript>',
'<!-- anchor linking to external file -->',
'<a href="https://github.com/cheeriojs/cheerio">External Link</a>',
'</noscript>',
'<p>Rocks!</p>',
'</body>',
].join('');
export const script: string = [
'<div>',
'<a>A</a>',
'<script>',
' var foo = "bar";',
'</script>',
'<b>B</b>',
'</div>',
].join('');
export const mixedText = '<a>1</a>TEXT<b>2</b>';
================================================
FILE: src/__tests__/deprecated.spec.ts
================================================
/**
* This file includes tests for deprecated APIs. The methods are expected to be
* removed in the next major release of Cheerio, but their stability should be
* maintained until that time.
*/
import { beforeEach, describe, expect, it } from 'vitest';
import { cheerio, food, fruits } from '../__fixtures__/fixtures.js';
describe('deprecated APIs', () => {
describe('cheerio module', () => {
describe('.parseHTML', () => {
it('(html) : should preserve content', () => {
const html = '<div>test div</div>';
expect(cheerio(cheerio.parseHTML(html)[0]).html()).toBe('test div');
});
});
describe('.merge', () => {
it('should be a function', () => {
expect(typeof cheerio.merge).toBe('function');
});
// #1674 - merge, wont accept Cheerio object
it('should be a able merge array and cheerio object', () => {
const ret = cheerio.merge<unknown>(cheerio(), ['elem1', 'elem2']);
expect(typeof ret).toBe('object');
expect(ret).toHaveLength(2);
});
it('(arraylike, arraylike) : should modify the first array, but not the second', () => {
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const ret = cheerio.merge(arr1, arr2);
expect(typeof ret).toBe('object');
expect(Array.isArray(ret)).toBe(true);
expect(ret).toBe(arr1);
expect(arr1).toHaveLength(6);
expect(arr2).toHaveLength(3);
});
it('(arraylike, arraylike) : should handle objects that arent arrays, but are arraylike', () => {
const arr1: ArrayLike<string> = {
length: 3,
0: 'a',
1: 'b',
2: 'c',
};
const arr2 = {
length: 3,
0: 'd',
1: 'e',
2: 'f',
};
cheerio.merge(arr1, arr2);
expect(arr1).toHaveLength(6);
expect(arr1[3]).toBe('d');
expect(arr1[4]).toBe('e');
expect(arr1[5]).toBe('f');
expect(arr2).toHaveLength(3);
});
it('(?, ?) : should gracefully reject invalid inputs', () => {
expect(cheerio.merge([4], 3 as never)).toBeUndefined();
expect(cheerio.merge({} as never, {} as never)).toBeUndefined();
expect(cheerio.merge([], {} as never)).toBeUndefined();
expect(cheerio.merge({} as never, [])).toBeUndefined();
const fakeArray = { length: 3, 0: 'a', 1: 'b', 3: 'd' };
expect(cheerio.merge(fakeArray, [])).toBeUndefined();
expect(cheerio.merge([], fakeArray)).toBeUndefined();
expect(cheerio.merge({ length: '7' } as never, [])).toBeUndefined();
expect(cheerio.merge({ length: -1 }, [])).toBeUndefined();
});
it('(?, ?) : should no-op on invalid inputs', () => {
const fakeArray1 = { length: 3, 0: 'a', 1: 'b', 3: 'd' };
cheerio.merge(fakeArray1, []);
expect(fakeArray1).toHaveLength(3);
expect(fakeArray1[0]).toBe('a');
expect(fakeArray1[1]).toBe('b');
expect(fakeArray1[3]).toBe('d');
cheerio.merge([], fakeArray1);
expect(fakeArray1).toHaveLength(3);
expect(fakeArray1[0]).toBe('a');
expect(fakeArray1[1]).toBe('b');
expect(fakeArray1[3]).toBe('d');
});
});
describe('.contains', () => {
let $: typeof cheerio;
beforeEach(() => {
$ = cheerio.load(food);
});
it('(container, contained) : should correctly detect the provided element', () => {
const $food = $('#food');
const $fruits = $('#fruits');
const $apple = $('.apple');
expect(cheerio.contains($food[0], $fruits[0])).toBe(true);
expect(cheerio.contains($food[0], $apple[0])).toBe(true);
});
it('(container, other) : should not detect elements that are not contained', () => {
const $fruits = $('#fruits');
const $vegetables = $('#vegetables');
const $apple = $('.apple');
expect(cheerio.contains($vegetables[0], $apple[0])).toBe(false);
expect(cheerio.contains($fruits[0], $vegetables[0])).toBe(false);
expect(cheerio.contains($vegetables[0], $fruits[0])).toBe(false);
expect(cheerio.contains($fruits[0], $fruits[0])).toBe(false);
expect(cheerio.contains($vegetables[0], $vegetables[0])).toBe(false);
});
});
describe('.root', () => {
it('returns an empty selection', () => {
const $empty = cheerio.root();
expect($empty).toHaveLength(1);
expect($empty[0].children).toHaveLength(0);
});
});
});
describe('Cheerio function', () => {
it('.load', () => {
const $1 = cheerio.load(fruits);
const $2 = $1.load('<div><p>Some <a>text</a>.</p></div>');
expect($2('a')).toHaveLength(1);
});
/**
* The `.html` static method defined on the "loaded" Cheerio factory
* function is deprecated.
*
* In order to promote consistency with the jQuery library, users are
* encouraged to instead use the instance method of the same name.
*
* @example
*
* ```js
* const $ = cheerio.load('<h1>Hello, <span>world</span>.</h1>');
*
* $('h1').html();
* //=> 'Hello, <span>world</span>.'
* ```
*
* @example <caption>To render the markup of an entire document, invoke the
* `html` function exported by the Cheerio module with a "root"
* selection.</caption>
*
* ```js
* cheerio.html($.root());
* //=> '<html><head></head><body><h1>Hello, <span>world</span>.</h1></body></html>'
* ```
*/
describe('.html - deprecated API', () => {
it('() : of empty cheerio object should return null', () => {
/*
* Note: the direct invocation of the Cheerio constructor function is
* also deprecated.
*/
const $ = cheerio();
expect($.html()).toBe(null);
});
it('(selector) : should return the outerHTML of the selected element', () => {
const $ = cheerio.load(fruits);
expect($.html('.pear')).toBe('<li class="pear">Pear</li>');
});
});
/**
* The `.xml` static method defined on the "loaded" Cheerio factory function
* is deprecated. Users are encouraged to instead use the `xml` function
* exported by the Cheerio module.
*
* @example
*
* ```js
* cheerio.xml($.root());
* ```
*/
describe('.xml - deprecated API', () => {
it('() : renders XML', () => {
const $ = cheerio.load('<foo></foo>', { xmlMode: true });
expect($.xml()).toBe('<foo/>');
});
});
/**
* The `.text` static method defined on the "loaded" Cheerio factory
* function is deprecated.
gitextract_2mrqq2gl/
├── .gitattributes
├── .github/
│ ├── FUNDING.yml
│ ├── dependabot.yml
│ ├── issue_template.md
│ └── workflows/
│ ├── benchmark.yml
│ ├── ci.yml
│ ├── codeql.yml
│ ├── dependabot-automerge.yml
│ ├── lint.yml
│ ├── site.yml
│ └── sponsors.yml
├── .gitignore
├── .husky/
│ ├── .gitignore
│ └── pre-commit
├── CONTRIBUTING.md
├── LICENSE
├── Readme.md
├── SECURITY.md
├── benchmark/
│ ├── benchmark.ts
│ └── documents/
│ └── jquery.html
├── biome.json
├── eslint.config.js
├── package.json
├── scripts/
│ └── fetch-sponsors.mts
├── src/
│ ├── __fixtures__/
│ │ └── fixtures.ts
│ ├── __tests__/
│ │ ├── deprecated.spec.ts
│ │ └── xml.spec.ts
│ ├── api/
│ │ ├── attributes.spec.ts
│ │ ├── attributes.ts
│ │ ├── css.spec.ts
│ │ ├── css.ts
│ │ ├── extract.spec.ts
│ │ ├── extract.ts
│ │ ├── forms.spec.ts
│ │ ├── forms.ts
│ │ ├── manipulation.spec.ts
│ │ ├── manipulation.ts
│ │ ├── traversing.spec.ts
│ │ └── traversing.ts
│ ├── cheerio.spec.ts
│ ├── cheerio.ts
│ ├── index-browser.mts
│ ├── index.spec.ts
│ ├── index.ts
│ ├── load-parse.ts
│ ├── load.spec.ts
│ ├── load.ts
│ ├── options.ts
│ ├── parse.spec.ts
│ ├── parse.ts
│ ├── parsers/
│ │ └── parse5-adapter.ts
│ ├── slim.ts
│ ├── static.spec.ts
│ ├── static.ts
│ ├── types.ts
│ ├── utils.spec.ts
│ └── utils.ts
├── tsconfig.json
├── tsconfig.typedoc.json
├── vitest.config.ts
└── website/
├── README.md
├── astro.config.mjs
├── package.json
├── sponsors.json
├── src/
│ ├── components/
│ │ ├── Features.astro
│ │ ├── Footer.astro
│ │ ├── Hero.astro
│ │ ├── LiveEditor.astro
│ │ ├── Navbar.astro
│ │ ├── Sidebar.astro
│ │ ├── Sponsors.astro
│ │ ├── TableOfContents.astro
│ │ ├── Testimonials.astro
│ │ └── live-code.tsx
│ ├── content/
│ │ ├── blog/
│ │ │ ├── 2023-02-13-new-website.md
│ │ │ └── 2024-08-07-version-1.md
│ │ ├── config.ts
│ │ └── docs/
│ │ ├── advanced/
│ │ │ ├── configuring-cheerio.md
│ │ │ ├── extending-cheerio.md
│ │ │ └── extract.md
│ │ ├── basics/
│ │ │ ├── loading.md
│ │ │ ├── manipulation.md
│ │ │ ├── selecting.md
│ │ │ └── traversing.mdx
│ │ └── intro.md
│ ├── env.d.ts
│ ├── layouts/
│ │ ├── BaseLayout.astro
│ │ ├── BlogLayout.astro
│ │ └── DocsLayout.astro
│ ├── pages/
│ │ ├── blog/
│ │ │ ├── [slug].astro
│ │ │ ├── index.astro
│ │ │ └── rss.xml.ts
│ │ ├── docs/
│ │ │ ├── [slug].astro
│ │ │ ├── advanced/
│ │ │ │ └── [slug].astro
│ │ │ ├── api/
│ │ │ │ └── [...slug].astro
│ │ │ └── basics/
│ │ │ └── [slug].astro
│ │ └── index.astro
│ ├── plugins/
│ │ ├── rehype-external-links.ts
│ │ ├── remark-admonitions.ts
│ │ ├── remark-fix-typedoc-links.ts
│ │ └── remark-live-code.ts
│ └── styles/
│ └── global.css
├── tsconfig.json
└── typedoc.json
SYMBOL INDEX (184 symbols across 29 files)
FILE: benchmark/benchmark.ts
type SuiteOptions (line 21) | type SuiteOptions<T> = T extends void
function benchmark (line 31) | async function benchmark<T = void>(
constant DIVS_MARKUP (line 80) | const DIVS_MARKUP = '<div>'.repeat(50);
method test (line 114) | test($, $lis) {
method setup (line 122) | setup($) {
method test (line 125) | test($) {
method test (line 132) | test(_, $lis) {
method test (line 138) | test(_, $lis) {
method test (line 145) | test(_, $lis) {
constant HTML_INDEPENDENT_MARKUP (line 150) | const HTML_INDEPENDENT_MARKUP =
method test (line 157) | test(_, $lis) {
method test (line 236) | test(_, $lis) {
method test (line 247) | test(_, $lis) {
method test (line 256) | test(_, $lis) {
method test (line 263) | test($, $lis) {
method test (line 284) | test(_, $lis) {
FILE: src/__tests__/xml.spec.ts
function xml (line 5) | function xml(str: string, options?: CheerioOptions) {
function dom (line 11) | function dom(str: string, options?: CheerioOptions) {
FILE: src/api/attributes.spec.ts
function withClass (line 15) | function withClass(attr: string) {
FILE: src/api/attributes.ts
function getAttr (line 50) | function getAttr(
function setAttr (line 95) | function setAttr(el: Element, name: string, value: string | null) {
function attr (line 188) | function attr<T extends AnyNode>(
function getProp (line 238) | function getProp(
function setProp (line 260) | function setProp(el: Element, name: string, value: unknown, xmlMode?: bo...
type StyleProp (line 277) | interface StyleProp {
function prop (line 412) | function prop<T extends AnyNode>(
type DataElement (line 533) | interface DataElement extends Element {
function setData (line 546) | function setData(
function readAllData (line 568) | function readAllData(el: DataElement): unknown {
function readData (line 595) | function readData(el: DataElement, name: string): unknown {
function parseDataValue (line 618) | function parseDataValue(value: string): unknown {
function data (line 719) | function data<T extends AnyNode>(
function val (line 788) | function val<T extends AnyNode>(
function removeAttribute (line 840) | function removeAttribute(elem: Element, name: string) {
function splitNames (line 853) | function splitNames(names?: string): string[] {
function removeAttr (line 876) | function removeAttr<T extends AnyNode>(
function hasClass (line 912) | function hasClass<T extends AnyNode>(
function addClass (line 958) | function addClass<T extends AnyNode, R extends ArrayLike<T>>(
function removeClass (line 1026) | function removeClass<T extends AnyNode, R extends ArrayLike<T>>(
function toggleClass (line 1097) | function toggleClass<T extends AnyNode, R extends ArrayLike<T>>(
FILE: src/api/css.ts
function css (line 66) | function css<T extends AnyNode>(
function setCss (line 100) | function setCss(
function getCss (line 151) | function getCss(
function stringify (line 181) | function stringify(obj: Record<string, string>): string {
function parse (line 196) | function parse(styles: string): Record<string, string> {
FILE: src/api/extract.spec.ts
type RedSelObject (line 5) | interface RedSelObject {
type RedSelMultipleObject (line 10) | interface RedSelMultipleObject {
FILE: src/api/extract.ts
type ExtractDescriptorFn (line 5) | type ExtractDescriptorFn = (
type ExtractDescriptor (line 12) | interface ExtractDescriptor {
type ExtractValue (line 17) | type ExtractValue = string | ExtractDescriptor | [string | ExtractDescri...
type ExtractMap (line 20) | type ExtractMap = Record<string, ExtractValue>;
type ExtractedValue (line 22) | type ExtractedValue<V extends ExtractValue> = V extends [
type ExtractedMap (line 39) | type ExtractedMap<M extends ExtractMap> = {
function getExtractDescr (line 43) | function getExtractDescr(
function extract (line 64) | function extract<M extends ExtractMap, T extends AnyNode>(
FILE: src/api/forms.ts
function serialize (line 26) | function serialize<T extends AnyNode>(this: Cheerio<T>): string {
function serializeArray (line 54) | function serializeArray<T extends AnyNode>(
FILE: src/api/manipulation.ts
function _makeDomArray (line 35) | function _makeDomArray<T extends AnyNode>(
function _insert (line 78) | function _insert(
function uniqueSplice (line 126) | function uniqueSplice(
function appendTo (line 208) | function appendTo<T extends AnyNode>(
function prependTo (line 241) | function prependTo<T extends AnyNode>(
function _wrap (line 308) | function _wrap(
function unwrap (line 515) | function unwrap<T extends AnyNode>(
function wrapAll (line 578) | function wrapAll<T extends AnyNode>(
function after (line 640) | function after<T extends AnyNode>(
function insertAfter (line 693) | function insertAfter<T extends AnyNode>(
function before (line 749) | function before<T extends AnyNode>(
function insertBefore (line 802) | function insertBefore<T extends AnyNode>(
function remove (line 854) | function remove<T extends AnyNode>(
function replaceWith (line 890) | function replaceWith<T extends AnyNode>(
function empty (line 938) | function empty<T extends AnyNode>(this: Cheerio<T>): Cheerio<T> {
function html (line 986) | function html<T extends AnyNode>(
function toString (line 1016) | function toString<T extends AnyNode>(this: Cheerio<T>): string {
function text (line 1061) | function text<T extends AnyNode>(
function clone (line 1102) | function clone<T extends AnyNode>(this: Cheerio<T>): Cheerio<T> {
FILE: src/api/traversing.spec.ts
function getText (line 17) | function getText(el: Cheerio<Element>) {
FILE: src/api/traversing.ts
function find (line 48) | function find<T extends AnyNode>(
function _findBySelector (line 80) | function _findBySelector<T extends AnyNode>(
function _getMatcher (line 115) | function _getMatcher<P>(
function _matchUntil (line 173) | function _matchUntil(
function _removeDuplicates (line 218) | function _removeDuplicates<T extends AnyNode>(elems: T[]): T[] {
function closest (line 336) | function closest<T extends AnyNode>(
function contents (line 599) | function contents<T extends AnyNode>(
function each (line 633) | function each<T>(
function map (line 669) | function map<T, M>(
function getFilterFn (line 691) | function getFilterFn<T>(
function filter (line 770) | function filter<T>(
function filterArray (line 787) | function filterArray<T>(
function is (line 810) | function is<T>(
function not (line 858) | function not<T extends AnyNode>(
function has (line 899) | function has(
function first (line 925) | function first<T extends AnyNode>(this: Cheerio<T>): Cheerio<T> {
function last (line 943) | function last<T>(this: Cheerio<T>): Cheerio<T> {
function eq (line 966) | function eq<T>(this: Cheerio<T>, i: number): Cheerio<T> {
function get (line 1008) | function get<T>(this: Cheerio<T>, i?: number): T | T[] {
function toArray (line 1027) | function toArray<T>(this: Cheerio<T>): T[] {
function index (line 1049) | function index<T extends AnyNode>(
function slice (line 1095) | function slice<T>(
function end (line 1118) | function end<T>(this: Cheerio<T>): Cheerio<AnyNode> {
function add (line 1138) | function add<S extends AnyNode, T extends AnyNode>(
function addBack (line 1164) | function addBack<T extends AnyNode>(
FILE: src/cheerio.spec.ts
type Cheerio (line 8) | interface Cheerio<T> {
function testAppleSelect (line 17) | function testAppleSelect($apple: ArrayLike<Element>) {
FILE: src/cheerio.ts
type MethodsType (line 11) | type MethodsType = typeof Attributes &
method constructor (line 59) | constructor(
type Cheerio (line 116) | interface Cheerio<T> extends MethodsType, Iterable<T> {
FILE: src/index.spec.ts
function noop (line 6) | function noop() {
function getPromise (line 11) | function getPromise() {
constant TEST_HTML (line 20) | const TEST_HTML = '<h1>Hello World</h1><a href="link">Example</a>';
constant TEST_HTML_UTF16 (line 21) | const TEST_HTML_UTF16 = Buffer.from(TEST_HTML, 'utf16le');
constant TEST_HTML_UTF16_BOM (line 22) | const TEST_HTML_UTF16_BOM = Buffer.from([
function createTestServer (line 120) | function createTestServer(
FILE: src/index.ts
function loadBuffer (line 57) | function loadBuffer(
function _stringStream (line 70) | function _stringStream(
function stringStream (line 142) | function stringStream(
type DecodeStreamOptions (line 150) | interface DecodeStreamOptions extends CheerioOptions {
function decodeStream (line 165) | function decodeStream(
type UndiciStreamOptions (line 183) | type UndiciStreamOptions = Omit<
type CheerioRequestOptions (line 189) | interface CheerioRequestOptions extends DecodeStreamOptions {
function fromURL (line 220) | async function fromURL(
FILE: src/load.ts
type StaticType (line 15) | type StaticType = typeof staticMethods;
type CheerioAPI (line 23) | interface CheerioAPI extends StaticType {
function getLoad (line 115) | function getLoad(
function isNode (line 279) | function isNode(obj: unknown): obj is AnyNode {
FILE: src/options.ts
type HTMLParser2Options (line 13) | interface HTMLParser2Options
type CheerioOptions (line 27) | interface CheerioOptions
type InternalOptions (line 90) | interface InternalOptions
function flattenOptions (line 114) | function flattenOptions(
FILE: src/parse.spec.ts
function rootTest (line 50) | function rootTest(root: Document) {
FILE: src/parse.ts
function getParse (line 16) | function getParse(
function update (line 71) | function update(
FILE: src/parsers/parse5-adapter.ts
function parseWithParse5 (line 20) | function parseWithParse5(
function renderWithParse5 (line 45) | function renderWithParse5(dom: AnyNode | ArrayLike<AnyNode>): string {
FILE: src/static.ts
function render (line 21) | function render(
function isOptions (line 38) | function isOptions(
function html (line 72) | function html(
function xml (line 104) | function xml(
function text (line 124) | function text(
function parseHTML (line 159) | function parseHTML(
function root (line 203) | function root(this: CheerioAPI): Cheerio<Document> {
function contains (line 218) | function contains(container: AnyNode, contained: AnyNode): boolean {
function extract (line 248) | function extract<M extends ExtractMap>(
type Writable (line 255) | type Writable<T> = { -readonly [P in keyof T]: T[P] };
function merge (line 267) | function merge<T>(
function isArrayLike (line 291) | function isArrayLike(item: unknown): item is ArrayLike<unknown> {
FILE: src/types.ts
type LowercaseLetters (line 3) | type LowercaseLetters =
type AlphaNumeric (line 31) | type AlphaNumeric =
type SelectorSpecial (line 36) | type SelectorSpecial = '.' | '#' | ':' | '|' | '>' | '+' | '~' | '[';
type SelectorType (line 41) | type SelectorType =
type BasicAcceptedElems (line 49) | type BasicAcceptedElems<T extends AnyNode> = ArrayLike<T> | T | string;
type AcceptedElems (line 51) | type AcceptedElems<T extends AnyNode> =
type FilterFunction (line 56) | type FilterFunction<T> = (this: T, i: number, el: T) => boolean;
type AcceptedFilters (line 58) | type AcceptedFilters<T> = string | FilterFunction<T> | T | Cheerio<T>;
FILE: src/utils.ts
function isCheerio (line 11) | function isCheerio<T>(
function camelCase (line 25) | function camelCase(str: string): string {
function cssCase (line 38) | function cssCase(str: string): string {
function domEach (line 54) | function domEach<
type CharacterCode (line 63) | const enum CharacterCode {
function isHtml (line 82) | function isHtml(str: string): boolean {
FILE: website/src/components/live-code.tsx
type LiveCodeProps (line 9) | interface LiveCodeProps {
function ResetButton (line 13) | function ResetButton() {
function RunButton (line 30) | function RunButton() {
function Toolbar (line 50) | function Toolbar() {
function LiveCode (line 64) | function LiveCode({ code }: LiveCodeProps) {
FILE: website/src/pages/blog/rss.xml.ts
function GET (line 6) | async function GET(context: APIContext) {
FILE: website/src/plugins/rehype-external-links.ts
function visitExternalLink (line 4) | function visitExternalLink(node: Element): void {
function transformer (line 19) | function transformer(tree: Root): void {
function rehypeExternalLinks (line 29) | function rehypeExternalLinks() {
FILE: website/src/plugins/remark-admonitions.ts
type DirectiveData (line 4) | interface DirectiveData {
type DirectiveNode (line 10) | interface DirectiveNode {
type DirectiveChild (line 17) | interface DirectiveChild {
constant ADMONITION_TYPES (line 24) | const ADMONITION_TYPES = ['note', 'tip', 'warning', 'danger', 'info'] as...
function visitAdmonition (line 26) | function visitAdmonition(node: unknown): void {
function transformer (line 73) | function transformer(tree: Root): void {
function remarkAdmonitions (line 83) | function remarkAdmonitions() {
FILE: website/src/plugins/remark-fix-typedoc-links.ts
function visitTypedocLink (line 6) | function visitTypedocLink(node: Link): void {
function transformer (line 13) | function transformer(tree: Root): void {
function remarkFixTypedocLinks (line 23) | function remarkFixTypedocLinks() {
FILE: website/src/plugins/remark-live-code.ts
type MdxJsxAttribute (line 4) | interface MdxJsxAttribute {
type MdxJsxFlowElement (line 10) | interface MdxJsxFlowElement {
function visitLiveCode (line 17) | function visitLiveCode(
function transformer (line 54) | function transformer(tree: Root): void {
function remarkLiveCode (line 71) | function remarkLiveCode() {
Condensed preview — 104 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (766K chars).
[
{
"path": ".gitattributes",
"chars": 101,
"preview": "# Enforce Unix newlines\n* text=auto eol=lf\n\nbenchmark/documents/* binary\nbenchmark/jquery*.js binary\n"
},
{
"path": ".github/FUNDING.yml",
"chars": 51,
"preview": "github: [cheeriojs, fb55]\nopen_collective: cheerio\n"
},
{
"path": ".github/dependabot.yml",
"chars": 419,
"preview": "version: 2\nupdates:\n - package-ecosystem: npm\n directory: '/'\n schedule:\n interval: daily\n open-pull-requ"
},
{
"path": ".github/issue_template.md",
"chars": 493,
"preview": "<!-- Thanks for your interest in cheerio!\n\nPlease note that issues should be primarily used for tracking bugs and featur"
},
{
"path": ".github/workflows/benchmark.yml",
"chars": 708,
"preview": "name: Benchmark\n\non:\n push:\n branches-ignore:\n - 'dependabot/**'\n pull_request:\n\nenv:\n FORCE_COLOR: 2\n\npermis"
},
{
"path": ".github/workflows/ci.yml",
"chars": 1272,
"preview": "name: CI\n\non:\n push:\n branches-ignore:\n - 'dependabot/**'\n pull_request:\n\nenv:\n FORCE_COLOR: 2\n NODE_COV: lt"
},
{
"path": ".github/workflows/codeql.yml",
"chars": 687,
"preview": "name: 'CodeQL'\n\non:\n push:\n branches:\n - main\n - '!dependabot/**'\n pull_request:\n # The branches below"
},
{
"path": ".github/workflows/dependabot-automerge.yml",
"chars": 1062,
"preview": "# Based on https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automaticall"
},
{
"path": ".github/workflows/lint.yml",
"chars": 837,
"preview": "name: Lint\n\non:\n push:\n branches-ignore:\n - 'dependabot/**'\n pull_request:\n\nenv:\n FORCE_COLOR: 2\n\npermissions"
},
{
"path": ".github/workflows/site.yml",
"chars": 1653,
"preview": "name: Deploy website to GitHub Pages\n\n# Based on https://raw.githubusercontent.com/actions/starter-workflows\n\non:\n # Ru"
},
{
"path": ".github/workflows/sponsors.yml",
"chars": 1169,
"preview": "name: Update Sponsors\n\non:\n schedule:\n # Run once a day, at 4pm\n - cron: '0 16 * * *'\n # Allow manual trigger\n "
},
{
"path": ".gitignore",
"chars": 185,
"preview": "node_modules\nnpm-debug.log\n.DS_Store\n.docusaurus\n.cache-loader\n/coverage\n/.tshy\n/.tshy-build\n/dist\n\n# Website build arti"
},
{
"path": ".husky/.gitignore",
"chars": 2,
"preview": "_\n"
},
{
"path": ".husky/pre-commit",
"chars": 11,
"preview": "lint-staged"
},
{
"path": "CONTRIBUTING.md",
"chars": 1661,
"preview": "# Contributing to Cheerio\n\nThanks for your interest in contributing to the project! Here's a rundown of how\nwe'd like to"
},
{
"path": "LICENSE",
"chars": 1081,
"preview": "MIT License\n\nCopyright (c) 2022 The Cheerio contributors\n\nPermission is hereby granted, free of charge, to any person ob"
},
{
"path": "Readme.md",
"chars": 7913,
"preview": "<h1 align=\"center\">cheerio</h1>\n\n<h5 align=\"center\">The fast, flexible, and elegant library for parsing and manipulating"
},
{
"path": "SECURITY.md",
"chars": 288,
"preview": "# Security Policy\n\n## Supported Versions\n\nOnly the latest release will receive security updates.\n\n## Reporting a Vulnera"
},
{
"path": "benchmark/benchmark.ts",
"chars": 7963,
"preview": "import fs from 'node:fs/promises';\nimport { Script } from 'node:vm';\nimport type { Element } from 'domhandler';\nimport {"
},
{
"path": "benchmark/documents/jquery.html",
"chars": 135200,
"preview": "<html\n class=\"js multiplebgs boxshadow cssgradients wf-klavikaweb-i7-active wf-klavikaweb-n7-active wf-sourcecodepro-n4"
},
{
"path": "biome.json",
"chars": 2971,
"preview": "{\n \"$schema\": \"https://biomejs.dev/schemas/2.4.6/schema.json\",\n \"vcs\": {\n \"enabled\": true,\n \"clientKind\": \"git\","
},
{
"path": "eslint.config.js",
"chars": 3588,
"preview": "import { fileURLToPath } from 'node:url'; // Added for .gitignore path\nimport { includeIgnoreFile } from '@eslint/compat"
},
{
"path": "package.json",
"chars": 4418,
"preview": "{\n \"name\": \"cheerio\",\n \"version\": \"1.2.0\",\n \"description\": \"The fast, flexible & elegant library for parsing and mani"
},
{
"path": "scripts/fetch-sponsors.mts",
"chars": 10655,
"preview": "/**\n * @file Script To fetch sponsor data from Open Collective and GitHub.\n *\n * Adapted from\n * https://github.com/"
},
{
"path": "src/__fixtures__/fixtures.ts",
"chars": 5528,
"preview": "import type { CheerioAPI } from '../load.js';\nimport { load } from '../load-parse.js';\n\n/** A Cheerio instance with no c"
},
{
"path": "src/__tests__/deprecated.spec.ts",
"chars": 9309,
"preview": "/**\n * This file includes tests for deprecated APIs. The methods are expected to be\n * removed in the next major release"
},
{
"path": "src/__tests__/xml.spec.ts",
"chars": 2174,
"preview": "import { describe, expect, it } from 'vitest';\nimport { load } from '../index.js';\nimport type { CheerioOptions } from '"
},
{
"path": "src/api/attributes.spec.ts",
"chars": 40415,
"preview": "import type { Element } from 'domhandler';\nimport { beforeEach, describe, expect, it } from 'vitest';\nimport {\n cheerio"
},
{
"path": "src/api/attributes.ts",
"chars": 29203,
"preview": "/**\n * Methods for getting and modifying attributes.\n *\n * @module cheerio/attributes\n */\n\nimport { type AnyNode, type E"
},
{
"path": "src/api/css.spec.ts",
"chars": 4749,
"preview": "import type { Element } from 'domhandler';\nimport { beforeEach, describe, expect, it } from 'vitest';\nimport { cheerio, "
},
{
"path": "src/api/css.ts",
"chars": 5659,
"preview": "import { type AnyNode, type Element, isTag } from 'domhandler';\nimport type { Cheerio } from '../cheerio.js';\nimport { d"
},
{
"path": "src/api/extract.spec.ts",
"chars": 7433,
"preview": "import { describe, expect, expectTypeOf, it } from 'vitest';\nimport * as fixtures from '../__fixtures__/fixtures.js';\nim"
},
{
"path": "src/api/extract.ts",
"chars": 2744,
"preview": "import type { AnyNode, Element } from 'domhandler';\nimport type { Cheerio } from '../cheerio.js';\nimport type { prop } f"
},
{
"path": "src/api/forms.spec.ts",
"chars": 4178,
"preview": "import { beforeEach, describe, expect, it } from 'vitest';\nimport { cheerio, forms } from '../__fixtures__/fixtures.js';"
},
{
"path": "src/api/forms.ts",
"chars": 3268,
"preview": "import { type AnyNode, isTag } from 'domhandler';\nimport type { Cheerio } from '../cheerio.js';\n\n/*\n * https://github.co"
},
{
"path": "src/api/manipulation.spec.ts",
"chars": 72130,
"preview": "import type { AnyNode, Element } from 'domhandler';\nimport { beforeEach, describe, expect, it } from 'vitest';\nimport {\n"
},
{
"path": "src/api/manipulation.ts",
"chars": 28533,
"preview": "/**\n * Methods for modifying the DOM structure.\n *\n * @module cheerio/manipulation\n */\n\nimport {\n type AnyNode,\n clone"
},
{
"path": "src/api/traversing.spec.ts",
"chars": 59166,
"preview": "import { type AnyNode, type Element, isText, type Text } from 'domhandler';\nimport { beforeEach, describe, expect, it } "
},
{
"path": "src/api/traversing.ts",
"chars": 30724,
"preview": "/**\n * Methods for traversing the DOM structure.\n *\n * @module cheerio/traversing\n */\n\nimport * as select from 'cheerio-"
},
{
"path": "src/cheerio.spec.ts",
"chars": 16170,
"preview": "import type { AnyNode, Element } from 'domhandler';\nimport { parseDOM } from 'htmlparser2';\nimport { describe, expect, i"
},
{
"path": "src/cheerio.ts",
"chars": 3786,
"preview": "import type { AnyNode, Document, ParentNode } from 'domhandler';\nimport * as Attributes from './api/attributes.js';\nimpo"
},
{
"path": "src/index-browser.mts",
"chars": 260,
"preview": "export * from './load-parse.js';\nexport type {\n AnyNode,\n Cheerio,\n CheerioAPI,\n CheerioOptions,\n Document,\n Eleme"
},
{
"path": "src/index.spec.ts",
"chars": 6204,
"preview": "import { createServer, type RequestListener, type Server } from 'node:http';\nimport { Writable } from 'node:stream';\nimp"
},
{
"path": "src/index.ts",
"chars": 8138,
"preview": "/**\n * @file Batteries-included version of Cheerio. This module includes several\n * convenience methods for loading do"
},
{
"path": "src/load-parse.ts",
"chars": 1566,
"preview": "import renderWithHtmlparser2 from 'dom-serializer';\nimport type { AnyNode } from 'domhandler';\nimport { parseDocument as"
},
{
"path": "src/load.spec.ts",
"chars": 988,
"preview": "import { describe, expect, it } from 'vitest';\nimport { load } from './index.js';\n\ndescribe('.load', () => {\n it('(html"
},
{
"path": "src/load.ts",
"chars": 8883,
"preview": "import type { AnyNode, Document, Element, ParentNode } from 'domhandler';\nimport { ElementType } from 'htmlparser2';\nimp"
},
{
"path": "src/options.ts",
"chars": 3670,
"preview": "import type { Options as SelectOptions } from 'cheerio-select';\nimport type { DomSerializerOptions } from 'dom-serialize"
},
{
"path": "src/parse.spec.ts",
"chars": 15566,
"preview": "import type { Document, Element } from 'domhandler';\nimport { parseDocument as parseWithHtmlparser2 } from 'htmlparser2'"
},
{
"path": "src/parse.ts",
"chars": 2465,
"preview": "import {\n type AnyNode,\n isDocument as checkIsDocument,\n Document,\n type ParentNode,\n} from 'domhandler';\nimport { r"
},
{
"path": "src/parsers/parse5-adapter.ts",
"chars": 2006,
"preview": "import {\n type AnyNode,\n type Document,\n isDocument,\n type ParentNode,\n} from 'domhandler';\nimport { parse as parseD"
},
{
"path": "src/slim.ts",
"chars": 1293,
"preview": "/**\n * @file Alternative entry point for Cheerio that always uses htmlparser2. This\n * way, parse5 won't be loaded, sa"
},
{
"path": "src/static.spec.ts",
"chars": 10967,
"preview": "import { beforeEach, describe, expect, it } from 'vitest';\nimport { cheerio, eleven, food } from './__fixtures__/fixture"
},
{
"path": "src/static.ts",
"chars": 8072,
"preview": "import type { AnyNode, Document } from 'domhandler';\nimport { textContent } from 'domutils';\nimport type { ExtractedMap,"
},
{
"path": "src/types.ts",
"chars": 1375,
"preview": "/** @file Types used in signatures of Cheerio methods. */\n\ntype LowercaseLetters =\n | 'a'\n | 'b'\n | 'c'\n | 'd'\n | '"
},
{
"path": "src/utils.spec.ts",
"chars": 1336,
"preview": "import { describe, expect, it } from 'vitest';\nimport * as utils from './utils.js';\n\ndescribe('util functions', () => {\n"
},
{
"path": "src/utils.ts",
"chars": 2556,
"preview": "import type { AnyNode } from 'domhandler';\nimport type { Cheerio } from './cheerio.js';\n\n/**\n * Checks if an object is a"
},
{
"path": "tsconfig.json",
"chars": 732,
"preview": "{\n \"compilerOptions\": {\n /* Basic Options */\n \"target\": \"es2019\",\n \"module\": \"node16\",\n \"moduleResolution\":"
},
{
"path": "tsconfig.typedoc.json",
"chars": 104,
"preview": "{\n \"extends\": \"./tsconfig.json\",\n \"exclude\": [\"*.config.ts\", \"*.spec.ts\", \"scripts/*\", \"website/*\"]\n}\n"
},
{
"path": "vitest.config.ts",
"chars": 405,
"preview": "import { defineConfig, type ViteUserConfig } from 'vitest/config';\n\nconst config: ViteUserConfig = defineConfig({\n test"
},
{
"path": "website/README.md",
"chars": 502,
"preview": "# Website\n\nThis website is built using [Docusaurus 2](https://docusaurus.io/), a modern\nstatic website generator.\n\n### I"
},
{
"path": "website/astro.config.mjs",
"chars": 1170,
"preview": "import mdx from '@astrojs/mdx';\nimport react from '@astrojs/react';\nimport sitemap from '@astrojs/sitemap';\nimport tailw"
},
{
"path": "website/package.json",
"chars": 1179,
"preview": "{\n \"name\": \"@cheerio/website\",\n \"description\": \"Documentation website for cheerio\",\n \"type\": \"module\",\n \"version\": \""
},
{
"path": "website/sponsors.json",
"chars": 2364,
"preview": "{\n \"headliner\": [\n {\n \"createdAt\": \"2022-06-24\",\n \"name\": \"Github\",\n \"image\": \"https://github.com/git"
},
{
"path": "website/src/components/Features.astro",
"chars": 2634,
"preview": "---\nimport { CodeXml, Globe, Zap } from '@lucide/astro';\n\nconst features = [\n {\n title: 'Proven syntax',\n descrip"
},
{
"path": "website/src/components/Footer.astro",
"chars": 3499,
"preview": "---\nimport { Image } from 'astro:assets';\nimport logo from '@/assets/orange-c.svg';\n\nconst footerLinks = {\n Docs: [\n "
},
{
"path": "website/src/components/Hero.astro",
"chars": 11409,
"preview": "---\n\nconst title = 'cheerio';\nconst tagline =\n 'The fast, flexible & elegant library for parsing and manipulating HTML "
},
{
"path": "website/src/components/LiveEditor.astro",
"chars": 279,
"preview": "---\n/**\n * Astro component that wraps LiveCode for use in markdown.\n * Usage in markdown: <LiveEditor>...</LiveEditor>\n "
},
{
"path": "website/src/components/Navbar.astro",
"chars": 5940,
"preview": "---\nimport { Image } from 'astro:assets';\nimport logo from '@/assets/orange-c.svg';\n\nconst navItems = [\n {\n label: '"
},
{
"path": "website/src/components/Sidebar.astro",
"chars": 11975,
"preview": "---\nimport { getCollection } from 'astro:content';\n\ninterface SidebarItem {\n label: string;\n href: string;\n}\n\ninterfac"
},
{
"path": "website/src/components/Sponsors.astro",
"chars": 2708,
"preview": "---\nimport { Image } from 'astro:assets';\nimport { Heart } from '@lucide/astro';\nimport sponsorsData from '../../sponsor"
},
{
"path": "website/src/components/TableOfContents.astro",
"chars": 1054,
"preview": "---\ninterface Props {\n headings: Array<{\n depth: number;\n slug: string;\n text: string;\n }>;\n}\n\nconst { headin"
},
{
"path": "website/src/components/Testimonials.astro",
"chars": 6235,
"preview": "---\nimport { Image } from 'astro:assets';\n\ninterface Tweet {\n id: string;\n name: string;\n user: string;\n github: str"
},
{
"path": "website/src/components/live-code.tsx",
"chars": 2509,
"preview": "import {\n SandpackCodeEditor,\n SandpackConsole,\n SandpackProvider,\n useSandpack,\n} from '@codesandbox/sandpack-react"
},
{
"path": "website/src/content/blog/2023-02-13-new-website.md",
"chars": 1318,
"preview": "---\nslug: new-website\ntitle: New Website, Who Dis?\nauthors: fb55\ntags: [website, intro]\n---\n\nCheerio has a new website, "
},
{
"path": "website/src/content/blog/2024-08-07-version-1.md",
"chars": 4384,
"preview": "---\nslug: cheerio-1.0\ntitle: Cheerio 1.0 Released, Batteries Included 🔋\nauthors: fb55\ntags: [release, announcement]\n---\n"
},
{
"path": "website/src/content/config.ts",
"chars": 621,
"preview": "import { defineCollection, z } from 'astro:content';\n\nconst docs = defineCollection({\n type: 'content',\n schema: z.obj"
},
{
"path": "website/src/content/docs/advanced/configuring-cheerio.md",
"chars": 5039,
"preview": "---\nsidebar_position: 2\ndescription: Configure Cheerio to work with different documents.\n---\n\n# Configuring Cheerio\n\nIn "
},
{
"path": "website/src/content/docs/advanced/extending-cheerio.md",
"chars": 1718,
"preview": "---\nsidebar_position: 999\ndescription: Create custom pseudo-classes and plugins.\n---\n\n# Extending Cheerio\n\nCheerio alrea"
},
{
"path": "website/src/content/docs/advanced/extract.md",
"chars": 5268,
"preview": "---\nsidebar_label: The `extract` method\nsidebar_position: 1\ndescription: Extract multiple values at once.\n---\n\n# Extract"
},
{
"path": "website/src/content/docs/basics/loading.md",
"chars": 4721,
"preview": "---\nsidebar_position: 2\ndescription: A walkthrough of different loading methods.\n---\n\n# Loading Documents\n\nIn this guide"
},
{
"path": "website/src/content/docs/basics/manipulation.md",
"chars": 8928,
"preview": "---\nsidebar_position: 5\ndescription: Methods to manipulate elements within a document.\n---\n\n# Manipulating the DOM\n\nNow "
},
{
"path": "website/src/content/docs/basics/selecting.md",
"chars": 3581,
"preview": "---\nsidebar_position: 3\ndescription: An introduction to CSS selectors.\n---\n\n# Selecting Elements\n\nCheerio allows users t"
},
{
"path": "website/src/content/docs/basics/traversing.mdx",
"chars": 11998,
"preview": "---\nsidebar_position: 4\ndescription: Traverse the DOM tree and filter elements.\n---\n\nimport { LiveCode } from '@/compone"
},
{
"path": "website/src/content/docs/intro.md",
"chars": 3408,
"preview": "---\nsidebar_position: 1\nsidebar_label: Introduction\n---\n\n# Welcome to Cheerio!\n\nLet's get a quick overview of **Cheerio "
},
{
"path": "website/src/env.d.ts",
"chars": 229,
"preview": "/* eslint-disable @typescript-eslint/triple-slash-reference */\n/* eslint-disable spaced-comment */\n/* eslint-disable mul"
},
{
"path": "website/src/layouts/BaseLayout.astro",
"chars": 1670,
"preview": "---\nimport '@/styles/global.css';\nimport { ViewTransitions } from 'astro:transitions';\nimport Footer from '@/components/"
},
{
"path": "website/src/layouts/BlogLayout.astro",
"chars": 1802,
"preview": "---\nimport BaseLayout from '@/layouts/BaseLayout.astro';\n\ninterface Props {\n title: string;\n description?: string;\n d"
},
{
"path": "website/src/layouts/DocsLayout.astro",
"chars": 7137,
"preview": "---\nimport '@/styles/global.css';\nimport { ViewTransitions } from 'astro:transitions';\nimport Footer from '@/components/"
},
{
"path": "website/src/pages/blog/[slug].astro",
"chars": 1019,
"preview": "---\nimport { getCollection, render } from 'astro:content';\nimport BlogLayout from '@/layouts/BlogLayout.astro';\n\nexport "
},
{
"path": "website/src/pages/blog/index.astro",
"chars": 5818,
"preview": "---\nimport { getCollection } from 'astro:content';\nimport BaseLayout from '@/layouts/BaseLayout.astro';\n\nconst posts = a"
},
{
"path": "website/src/pages/blog/rss.xml.ts",
"chars": 1208,
"preview": "import { getCollection } from 'astro:content';\nimport rss from '@astrojs/rss';\nimport type { APIContext } from 'astro';\n"
},
{
"path": "website/src/pages/docs/[slug].astro",
"chars": 705,
"preview": "---\nimport { getCollection, render } from 'astro:content';\nimport DocsLayout from '@/layouts/DocsLayout.astro';\n\nexport "
},
{
"path": "website/src/pages/docs/advanced/[slug].astro",
"chars": 739,
"preview": "---\nimport { getCollection, render } from 'astro:content';\nimport DocsLayout from '@/layouts/DocsLayout.astro';\n\nexport "
},
{
"path": "website/src/pages/docs/api/[...slug].astro",
"chars": 961,
"preview": "---\nimport { getCollection, render } from 'astro:content';\nimport DocsLayout from '@/layouts/DocsLayout.astro';\n\nexport "
},
{
"path": "website/src/pages/docs/basics/[slug].astro",
"chars": 735,
"preview": "---\nimport { getCollection, render } from 'astro:content';\nimport DocsLayout from '@/layouts/DocsLayout.astro';\n\nexport "
},
{
"path": "website/src/pages/index.astro",
"chars": 2367,
"preview": "---\nimport Features from '@/components/Features.astro';\nimport Hero from '@/components/Hero.astro';\nimport Sponsors from"
},
{
"path": "website/src/plugins/rehype-external-links.ts",
"chars": 867,
"preview": "import type { Element, Root } from 'hast';\nimport { visit } from 'unist-util-visit';\n\nfunction visitExternalLink(node: E"
},
{
"path": "website/src/plugins/remark-admonitions.ts",
"chars": 2078,
"preview": "import type { Root } from 'mdast';\nimport { visit } from 'unist-util-visit';\n\ninterface DirectiveData {\n hName?: string"
},
{
"path": "website/src/plugins/remark-fix-typedoc-links.ts",
"chars": 656,
"preview": "import type { Link, Root } from 'mdast';\nimport { visit } from 'unist-util-visit';\n\nconst markdownExtensionRe = /\\.md$/;"
},
{
"path": "website/src/plugins/remark-live-code.ts",
"chars": 1655,
"preview": "import type { Code, Parent, Root } from 'mdast';\nimport { visit } from 'unist-util-visit';\n\ninterface MdxJsxAttribute {\n"
},
{
"path": "website/src/styles/global.css",
"chars": 8614,
"preview": "@import \"tailwindcss\";\n\n@font-face {\n font-family: \"Inter\";\n font-style: normal;\n font-weight: 600;\n src: url(\"/font"
},
{
"path": "website/tsconfig.json",
"chars": 343,
"preview": "{\n \"extends\": \"astro/tsconfigs/strict\",\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"paths\": {\n \"@/*\": [\"src/*\""
},
{
"path": "website/typedoc.json",
"chars": 1331,
"preview": "{\n \"$schema\": \"https://typedoc.org/schema.json\",\n \"entryPoints\": [\"../src/index.ts\"],\n \"tsconfig\": \"../tsconfig.typed"
}
]
About this extraction
This page contains the full source code of the cheeriojs/cheerio GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 104 files (713.4 KB), approximately 187.4k tokens, and a symbol index with 184 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.