DE EN ES FR ID JA KO PT RU TH VI ZH

Cheerio API リファレンス

CheerioはjQueryのコア機能を高速で柔軟かつエレガントにサーバーサイドで実装したものです。Node.js環境でHTMLやXML文書を解析・操作するためのjQueryライクなAPIを提供します。

コア読み込み関数

cheerio.load(content, options?)

HTML/XMLコンテンツを読み込み、クエリと操作のためのCheerioAPIインスタンスを返します。

シグネチャ:

function load(
  content: string | AnyNode | AnyNode[] | Buffer,
  options?: CheerioOptions,
  isDocument?: boolean
): CheerioAPI

パラメータ:

名前 デフォルト 説明
content string | AnyNode | AnyNode[] | Buffer - 解析するHTML/XMLコンテンツ
options CheerioOptions {} パーサーと動作のオプション
isDocument boolean true コンテンツを完全な文書として扱うかどうか

戻り値: CheerioAPI - jQueryライクなメソッドを持つCheerioインスタンス

例:

import * as cheerio from 'cheerio';

// Basic HTML loading
const $ = cheerio.load('<ul><li>Apple</li><li>Orange</li></ul>');

// With options
const $ = cheerio.load('<xml><item>data</item></xml>', {
  xmlMode: true,
  decodeEntities: false
});

// Loading from buffer
const buffer = Buffer.from('<div>Hello</div>');
const $ = cheerio.load(buffer);

よくある注意点:

要素の選択

$(selector, context?, root?)

読み込まれた文書からCSSセレクタを使用して要素を選択します。jQueryの$()関数と同様です。

シグネチャ:

function $(
  selector: string | AnyNode | AnyNode[] | Cheerio<AnyNode>,
  context?: string | AnyNode | Cheerio<AnyNode>,
  root?: string | Document
): Cheerio<Element>

パラメータ:

名前 デフォルト 説明
selector string | AnyNode | AnyNode[] | Cheerio<AnyNode> - CSSセレクタまたは選択する要素
context string | AnyNode | Cheerio<AnyNode> document 検索対象のコンテキスト
root string | Document - コンテキストのルート文書

戻り値: Cheerio<Element> - マッチした要素のコレクション

例:

// Basic selection
$('li').length; // Number of <li> elements
$('.apple').text(); // Text content of first element with class 'apple'

// With context
$('li', '#fruits').addClass('fruit'); // Find <li> within #fruits

// Complex selectors
$('li:nth-child(2n)').css('color', 'red'); // Every other <li>
$('a[href^="https://"]').attr('target', '_blank'); // External links

属性の操作

.attr(name, value?)

マッチした要素の属性を取得または設定します。

シグネチャ:

// Get attribute
function attr(name: string): string | undefined;
// Set attribute
function attr(name: string, value: string | null | ((i: number, attr: string) => string | null)): Cheerio<T>;
// Set multiple attributes
function attr(attributes: Record<string, string | null>): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
name string | Record<string, string | null> - 属性名またはオブジェクトマップ
value string | null | function - 設定する値、削除する場合はnull、または関数

戻り値: string \| undefined \| Cheerio<T> - 属性値(getter)またはCheerioインスタンス(setter)

例:

// Get attribute
const href = $('a').attr('href'); // Gets href of first <a>

// Set attribute
$('img').attr('alt', 'Description'); // Sets alt text
$('a').attr('href', null); // Removes href attribute

// Multiple attributes
$('input').attr({
  type: 'text',
  placeholder: 'Enter name',
  required: 'required'
});

// Function-based setting
$('img').attr('src', (i, src) => src.replace('http://', 'https://'));

よくある注意点:

.prop(name, value?)

DOM要素のプロパティを取得または設定します。checkedselectedなどの特別なプロパティを処理します。

シグネチャ:

// Get property
function prop(name: string): any;
// Set property
function prop(name: string, value: any): Cheerio<T>;
// Set multiple properties
function prop(properties: Record<string, any>): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
name string | Record<string, any> - プロパティ名またはオブジェクトマップ
value any - 設定する値

戻り値: any \| Cheerio<T> - プロパティ値(getter)またはCheerioインスタンス(setter)

例:

// Get property
const isChecked = $('input[type="checkbox"]').prop('checked'); // true/false

// Set property
$('input[type="checkbox"]').prop('checked', true);
$('option').prop('selected', false);

// Special properties
$('a').prop('href'); // Resolved absolute URL
$('div').prop('outerHTML'); // Full HTML including the element
$('div').prop('innerHTML'); // Inner HTML content

.data(key, value?)

HTML5のdata-*属性の自動型変換を行いながら、データ属性を取得または設定します。

シグネチャ:

// Get all data
function data(): Record<string, unknown>;
// Get specific data
function data(key: string): unknown;
// Set data
function data(key: string, value: unknown): Cheerio<T>;
// Set multiple data
function data(values: Record<string, unknown>): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
key string | Record<string, unknown> - データキーまたはオブジェクトマップ
value unknown - 設定する値

戻り値: unknown \| Record<string, unknown> \| Cheerio<T> - データ値またはCheerioインスタンス

例:

// HTML: <div data-user-id="123" data-active="true">
const userId = $('.user').data('userId'); // 123 (number)
const isActive = $('.user').data('active'); // true (boolean)

// Set data
$('.user').data('lastSeen', new Date());
$('.user').data({
  role: 'admin',
  permissions: ['read', 'write']
});

// Camel case conversion
$('<div data-foo-bar="test">').data('fooBar'); // "test"

よくある注意点:

コンテンツの操作

.text(value?)

要素のテキストコンテンツを取得または設定します。すべてのHTMLタグを除去します。

シグネチャ:

// Get text
function text(): string;
// Set text
function text(value: string | number | ((i: number, text: string) => string | number)): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
value string | number | function - 設定するテキストコンテンツまたは関数

戻り値: string \| Cheerio<T> - テキストコンテンツ(getter)またはCheerioインスタンス(setter)

例:

// Get text content
const title = $('h1').text(); // "Welcome to My Site"

// Set text (HTML-safe)
$('h1').text('New <Title>'); // Displays: "New <Title>" (not rendered as HTML)

// Function-based setting
$('li').text((i, currentText) => `${i + 1}. ${currentText}`);

.html(value?)

要素の内部HTMLコンテンツを取得または設定します。

シグネチャ:

// Get HTML
function html(): string | null;
// Set HTML
function html(value: string | ((i: number, html: string) => string)): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
value string | function - 設定するHTMLコンテンツまたは関数

戻り値: string \| null \| Cheerio<T> - HTMLコンテンツ(getter)またはCheerioインスタンス(setter)

例:

// Get HTML
const content = $('.container').html(); // "<p>Hello <strong>world</strong></p>"

// Set HTML
$('.container').html('<p>New content</p>');

// Function-based setting
$('div').html((i, oldHtml) => `<span>Item ${i}</span>${oldHtml}`);

よくある注意点:

.val(value?)

フォーム要素(input、select、textarea)の値を取得または設定します。

シグネチャ:

// Get value
function val(): string | string[] | undefined;
// Set value
function val(value: string | string[]): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
value string | string[] - 設定する値(複数選択の場合は配列)

戻り値: string \| string[] \| undefined \| Cheerio<T> - フォームの値またはCheerioインスタンス

例:

// Get values
const inputValue = $('input[name="email"]').val(); // "user@example.com"
const selectedOptions = $('select[multiple]').val(); // ["option1", "option2"]

// Set values
$('input[type="text"]').val('New value');
$('select[multiple]').val(['option1', 'option3']); // Selects multiple options
$('textarea').val('Long text content...');

DOM操作

.append(content)

マッチした各要素の最後の子要素としてコンテンツを挿入します。

シグネチャ:

function append(
  ...contents: (
    | string
    | AnyNode
    | AnyNode[]
    | Cheerio<AnyNode>
    | ((i: number, html: string) => string | AnyNode | Cheerio<AnyNode>)
  )[]
): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
contents string | AnyNode | Cheerio | function - 追加するコンテンツ

戻り値: Cheerio<T> - 元のCheerioインスタンス

例:

// Append HTML string
$('ul').append('<li>New item</li>');

// Append multiple items
$('ul').append('<li>Item 1</li>', '<li>Item 2</li>');

// Append Cheerio object
const $newLi = $('<li>').text('Dynamic item');
$('ul').append($newLi);

// Function-based appending
$('div').append((i, html) => `<p>Section ${i + 1}</p>`);

.remove(selector?)

マッチした要素をDOMから削除します。

シグネチャ:

function remove(selector?: string): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
selector string - 削除をフィルタリングするオプションのセレクタ

戻り値: Cheerio<T> - 削除された要素

例:

// Remove all matched elements
$('.obsolete').remove();

// Remove with filtering
$('li').remove(':contains("delete")'); // Remove <li> containing "delete"

// Chain after removal
$('p').remove().appendTo('.archive'); // Move to archive

CSSとスタイリング

.css(property, value?)

要素のCSSスタイルを取得または設定します。

シグネチャ:

// Get style
function css(property: string): string | undefined;
// Set style
function css(property: string, value: string | ((i: number, style: string) => string)): Cheerio<T>;
// Set multiple styles
function css(properties: Record<string, string>): Cheerio<T>;
// Get multiple styles
function css(properties: string[]): Record<string, string>;

パラメータ:

名前 デフォルト 説明
property string | string[] | Record<string, string> - CSSプロパティ名、配列、またはオブジェクト
value string | function - 設定するCSS値または関数

戻り値: string \| Record<string, string> \| Cheerio<T> - CSS値またはCheerioインスタンス

例:

// Get computed style
const color = $('.highlight').css('color'); // "red"

// Set single style
$('.box').css('background-color', 'blue');

// Set multiple styles
$('.card').css({
  'border-radius': '8px',
  'box-shadow': '0 2px 4px rgba(0,0,0,0.1)',
  padding: '16px'
});

// Function-based setting
$('div').css('width', (i, width) => `${parseInt(width) + 10}px`);

.addClass(className)

マッチした要素にCSSクラスを追加します。

シグネチャ:

function addClass(
  className: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
className string | function - スペース区切りのクラス名または関数

戻り値: Cheerio<T> - メソッドチェーンのためのCheerioインスタンス

例:

// Add single class
$('.item').addClass('active');

// Add multiple classes
$('.card').addClass('highlighted featured');

// Function-based adding
$('li').addClass((i, currentClass) => {
  return i % 2 === 0 ? 'even' : 'odd';
});

.removeClass(className?)

マッチした要素からCSSクラスを削除します。

シグネチャ:

function removeClass(
  className?: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
className string | function - 削除するクラスまたは関数(省略すると全て削除)

戻り値: Cheerio<T> - メソッドチェーンのためのCheerioインスタンス

例:

// Remove specific class
$('.item').removeClass('active');

// Remove multiple classes
$('.card').removeClass('highlighted featured');

// Remove all classes
$('.temp').removeClass();

// Function-based removal
$('div').removeClass((i, currentClass) => {
  return currentClass.includes('temp-') ? currentClass : '';
});

.hasClass(className)

マッチした要素のいずれかが指定されたCSSクラスを持っているかチェックします。

シグネチャ:

function hasClass(className: string): boolean;

パラメータ:

名前 デフォルト 説明
className string - チェックするクラス名

戻り値: boolean - いずれかの要素がクラスを持っている場合はtrue

例:

// Check for class
if ($('.nav-item').hasClass('active')) {
  console.log('Found active navigation item');
}

// Conditional logic
$('.button').each(function() {
  if ($(this).hasClass('primary')) {
    $(this).css('font-weight', 'bold');
  }
});

トラバーサルとフィルタリング

.find(selector)

セレクタにマッチする子孫要素を検索します。

シグネチャ:

function find<T extends AnyNode>(selector: string): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
selector string - 検索するCSSセレクタ

戻り値: Cheerio<T> - 見つかった子孫要素のコレクション

例:

// Find descendants
const links = $('.nav').find('a'); // All <a> tags inside .nav

// Complex selectors
const activeLinks = $('.menu').find('li.active a[href]');

// Chain with other methods
$('.article').find('img').attr('loading', 'lazy');

.each(callback)

マッチした要素を反復処理し、それぞれに対してcallbackを実行します。

シグネチャ:

function each(
  callback: (this: T, i: number, el: T) => void | false
): Cheerio<T>;

パラメータ:

名前 デフォルト 説明
callback function - 各要素に対して実行する関数

戻り値: Cheerio<T> - 元のCheerioインスタンス

例:

// Basic iteration
$('li').each(function(i, el) {
  console.log(`Item ${i}: ${$(el).text()}`);
});

// Early termination
$('.item').each(function(i) {
  if ($(this).hasClass('stop')) return false; // Break loop
  $(this).addClass(`item-${i}`);
});

// Arrow function (note: `this` context differs)
$('img').each((i, img) => {
  $(img).attr('alt', `Image ${i + 1}`);
});

よくある注意点:

フォーム処理

.serialize()

フォーム要素をURL エンコードされたクエリ文字列にシリアライズします。

シグネチャ:

function serialize(): string;

戻り値: string - URL エンコードされたフォームデータ

例:

// Serialize entire form
const formData = $('form').serialize();
// "name=John&email=john%40example.com&subscribe=on"

// Serialize specific inputs
const inputData = $('input[type="text"], select').serialize();

.serializeArray()

フォーム要素を名前-値オブジェクトの配列にシリアライズします。

シグネチャ:

function serializeArray(): Array<{ name: string; value: string }>;

戻り値: Array<{ name: string; value: string }> - フォームデータオブジェクトの配列

例:

// Get structured form data
const formArray = $('form').serializeArray();
// [{ name: 'email', value: 'user@example.com' }, { name: 'subscribe', value: 'on' }]

// Convert to object
const formObject = {};
$('form').serializeArray().forEach(item => {
  formObject[item.name] = item.value;
});

よくある注意点: