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

Tài liệu tham khảo API Cheerio

Cheerio là một triển khai phía server nhanh, linh hoạt và tinh tế của các chức năng cốt lõi jQuery. Nó cung cấp một API quen thuộc giống jQuery để phân tích và thao tác với các tài liệu HTML và XML trong môi trường Node.js.

Các hàm tải cốt lõi

cheerio.load(content, options?)

Tải nội dung HTML/XML và trả về một instance CheerioAPI để truy vấn và thao tác.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
content string | AnyNode | AnyNode[] | Buffer - Nội dung HTML/XML cần phân tích
options CheerioOptions {} Tùy chọn parser và hành vi
isDocument boolean true Có nên coi nội dung như một tài liệu hoàn chỉnh hay không

Trả về: CheerioAPI - Một instance Cheerio với các phương thức giống jQuery

Ví dụ:

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);

Những lưu ý thường gặp:

Lựa chọn phần tử

$(selector, context?, root?)

Chọn các phần tử từ tài liệu đã tải bằng CSS selector, tương tự như hàm $() của jQuery.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
selector string | AnyNode | AnyNode[] | Cheerio<AnyNode> - CSS selector hoặc phần tử cần chọn
context string | AnyNode | Cheerio<AnyNode> document Ngữ cảnh để tìm kiếm trong đó
root string | Document - Tài liệu gốc cho ngữ cảnh

Trả về: Cheerio<Element> - Tập hợp các phần tử khớp

Ví dụ:

// 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

Thao tác thuộc tính

.attr(name, value?)

Lấy hoặc đặt thuộc tính trên các phần tử khớp.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
name string | Record<string, string | null> - Tên thuộc tính hoặc object map
value string | null | function - Giá trị cần đặt, null để xóa, hoặc function

Trả về: string \| undefined \| Cheerio<T> - Giá trị thuộc tính (getter) hoặc instance Cheerio (setter)

Ví dụ:

// 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://'));

Những lưu ý thường gặp:

.prop(name, value?)

Lấy hoặc đặt các thuộc tính trên các phần tử DOM, xử lý các thuộc tính đặc biệt như checked, selected, v.v.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
name string | Record<string, any> - Tên thuộc tính hoặc object map
value any - Giá trị cần đặt

Trả về: any \| Cheerio<T> - Giá trị thuộc tính (getter) hoặc instance Cheerio (setter)

Ví dụ:

// 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?)

Lấy hoặc đặt các thuộc tính data với chuyển đổi loại tự động cho các thuộc tính data-* của HTML5.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
key string | Record<string, unknown> - Khóa data hoặc object map
value unknown - Giá trị cần đặt

Trả về: unknown \| Record<string, unknown> \| Cheerio<T> - Giá trị data hoặc instance Cheerio

Ví dụ:

// 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"

Những lưu ý thường gặp:

Thao tác nội dung

.text(value?)

Lấy hoặc đặt nội dung văn bản của các phần tử, loại bỏ tất cả thẻ HTML.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
value string | number | function - Nội dung văn bản cần đặt hoặc function

Trả về: string \| Cheerio<T> - Nội dung văn bản (getter) hoặc instance Cheerio (setter)

Ví dụ:

// 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?)

Lấy hoặc đặt nội dung HTML bên trong của các phần tử.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
value string | function - Nội dung HTML cần đặt hoặc function

Trả về: string \| null \| Cheerio<T> - Nội dung HTML (getter) hoặc instance Cheerio (setter)

Ví dụ:

// 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}`);

Những lưu ý thường gặp:

.val(value?)

Lấy hoặc đặt giá trị của các phần tử form (input, select, textarea).

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
value string | string[] - Giá trị cần đặt (mảng cho multi-select)

Trả về: string \| string[] \| undefined \| Cheerio<T> - Giá trị form hoặc instance Cheerio

Ví dụ:

// 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...');

Thao tác DOM

.append(content)

Chèn nội dung làm phần tử con cuối cùng của mỗi phần tử khớp.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
contents string | AnyNode | Cheerio | function - Nội dung cần thêm vào

Trả về: Cheerio<T> - Instance Cheerio ban đầu

Ví dụ:

// 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?)

Xóa các phần tử khớp khỏi DOM.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
selector string - Selector tùy chọn để lọc việc xóa

Trả về: Cheerio<T> - Các phần tử đã bị xóa

Ví dụ:

// 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 và Styling

.css(property, value?)

Lấy hoặc đặt các style CSS trên các phần tử.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
property string | string[] | Record<string, string> - Tên thuộc tính CSS, mảng, hoặc object
value string | function - Giá trị CSS cần đặt hoặc function

Trả về: string \| Record<string, string> \| Cheerio<T> - Giá trị CSS hoặc instance Cheerio

Ví dụ:

// 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)

Thêm class CSS vào các phần tử khớp.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
className string | function - Tên class ngăn cách bằng dấu cách hoặc function

Trả về: Cheerio<T> - Instance Cheerio để móc nối

Ví dụ:

// 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?)

Xóa class CSS khỏi các phần tử khớp.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
className string | function - Class cần xóa, hoặc function (bỏ qua để xóa tất cả)

Trả về: Cheerio<T> - Instance Cheerio để móc nối

Ví dụ:

// 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)

Kiểm tra xem bất kỳ phần tử khớp nào có class CSS được chỉ định hay không.

Signature:

function hasClass(className: string): boolean;

Tham số:

Tên Loại Mặc định Mô tả
className string - Tên class cần kiểm tra

Trả về: boolean - True nếu bất kỳ phần tử nào có class đó

Ví dụ:

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

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

Traversal và Filtering

.find(selector)

Tìm kiếm các phần tử con cháu khớp với selector.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
selector string - CSS selector cần tìm kiếm

Trả về: Cheerio<T> - Tập hợp các phần tử con cháu được tìm thấy

Ví dụ:

// 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)

Lặp qua các phần tử khớp, thực thi callback cho mỗi phần tử.

Signature:

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

Tham số:

Tên Loại Mặc định Mô tả
callback function - Function thực thi cho mỗi phần tử

Trả về: Cheerio<T> - Instance Cheerio ban đầu

Ví dụ:

// 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}`);
});

Những lưu ý thường gặp:

Xử lý Form

.serialize()

Tuần tự hóa các phần tử form thành chuỗi query được mã hóa URL.

Signature:

function serialize(): string;

Trả về: string - Dữ liệu form được mã hóa URL

Ví dụ:

// 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()

Tuần tự hóa các phần tử form thành mảng các object name-value.

Signature:

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

Trả về: Array<{ name: string; value: string }> - Mảng các object dữ liệu form

Ví dụ:

// 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;
});

Những lưu ý thường gặp: