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

Cheerio API Reference

Cheerio เป็นการใช้งานฟังก์ชันหลักของ jQuery ที่รวดเร็ว ยืดหยุ่น และสวยงามสำหรับฝั่ง server โดยมี API ที่คุ้นเคยเหมือน jQuery สำหรับการแยกวิเคราะห์และจัดการเอกสาร HTML และ XML ใน environment ของ Node.js

Core Loading Functions

cheerio.load(content, options?)

โหลดเนื้อหา HTML/XML และส่งคืน CheerioAPI instance สำหรับการ query และจัดการข้อมูล

Signature:

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

Parameters:

Name Type Default Description
content string | AnyNode | AnyNode[] | Buffer - เนื้อหา HTML/XML ที่จะแยกวิเคราะห์
options CheerioOptions {} ตัวเลือกสำหรับ parser และพฤติกรรม
isDocument boolean true กำหนดว่าจะถือว่าเนื้อหาเป็นเอกสารที่สมบูรณ์หรือไม่

Returns: CheerioAPI - Cheerio instance ที่มี method เหมือน jQuery

Examples:

import * as cheerio from 'cheerio';

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

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

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

ข้อควรระวัง:

Element Selection

$(selector, context?, root?)

เลือก element จากเอกสารที่โหลดแล้วโดยใช้ CSS selector คล้ายกับฟังก์ชัน $() ของ jQuery

Signature:

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

Parameters:

Name Type Default Description
selector string | AnyNode | AnyNode[] | Cheerio<AnyNode> - CSS selector หรือ element ที่จะเลือก
context string | AnyNode | Cheerio<AnyNode> document บริบทที่จะค้นหาภายใน
root string | Document - เอกสารรากสำหรับบริบท

Returns: Cheerio<Element> - คอลเลคชันของ element ที่ตรงกัน

Examples:

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

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

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

Attribute Manipulation

.attr(name, value?)

ดึงหรือตั้งค่า attribute ใน element ที่ตรงกัน

Signature:

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

Parameters:

Name Type Default Description
name string | Record<string, string | null> - ชื่อ attribute หรือ object map
value string | null | function - ค่าที่จะตั้ง, null เพื่อลบ, หรือฟังก์ชัน

Returns: string \| undefined \| Cheerio<T> - ค่า attribute (getter) หรือ Cheerio instance (setter)

Examples:

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

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

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

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

ข้อควรระวัง:

.prop(name, value?)

ดึงหรือตั้งค่า property ใน DOM element โดยจัดการ property พิเศษเช่น checked, selected เป็นต้น

Signature:

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

Parameters:

Name Type Default Description
name string | Record<string, any> - ชื่อ property หรือ object map
value any - ค่าที่จะตั้ง

Returns: any \| Cheerio<T> - ค่า property (getter) หรือ Cheerio instance (setter)

Examples:

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

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

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

.data(key, value?)

ดึงหรือตั้งค่า data attribute พร้อมการแปลงประเภทอัตโนมัติสำหรับ HTML5 data-* attribute

Signature:

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

Parameters:

Name Type Default Description
key string | Record<string, unknown> - คีย์ข้อมูลหรือ object map
value unknown - ค่าที่จะตั้ง

Returns: unknown \| Record<string, unknown> \| Cheerio<T> - ค่าข้อมูลหรือ Cheerio instance

Examples:

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

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

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

ข้อควรระวัง:

Content Manipulation

.text(value?)

ดึงหรือตั้งค่าเนื้อหาข้อความของ element โดยลบ HTML tag ทั้งหมดออก

Signature:

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

Parameters:

Name Type Default Description
value string | number | function - เนื้อหาข้อความที่จะตั้งหรือฟังก์ชัน

Returns: string \| Cheerio<T> - เนื้อหาข้อความ (getter) หรือ Cheerio instance (setter)

Examples:

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

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

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

.html(value?)

ดึงหรือตั้งค่าเนื้อหา inner HTML ของ element

Signature:

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

Parameters:

Name Type Default Description
value string | function - เนื้อหา HTML ที่จะตั้งหรือฟังก์ชัน

Returns: string \| null \| Cheerio<T> - เนื้อหา HTML (getter) หรือ Cheerio instance (setter)

Examples:

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

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

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

ข้อควรระวัง:

.val(value?)

ดึงหรือตั้งค่าของ form element (input, select, textarea)

Signature:

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

Parameters:

Name Type Default Description
value string | string[] - ค่าที่จะตั้ง (array สำหรับ multi-select)

Returns: string \| string[] \| undefined \| Cheerio<T> - ค่าของฟอร์มหรือ Cheerio instance

Examples:

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

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

DOM Manipulation

.append(content)

แทรกเนื้อหาเป็น child สุดท้ายของแต่ละ element ที่ตรงกัน

Signature:

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

Parameters:

Name Type Default Description
contents string | AnyNode | Cheerio | function - เนื้อหาที่จะเพิ่ม

Returns: Cheerio<T> - Cheerio instance เดิม

Examples:

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

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

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

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

.remove(selector?)

ลบ element ที่ตรงกันออกจาก DOM

Signature:

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

Parameters:

Name Type Default Description
selector string - selector ตัวเลือกสำหรับกรองการลบ

Returns: Cheerio<T> - Element ที่ถูกลบ

Examples:

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

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

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

CSS and Styling

.css(property, value?)

ดึงหรือตั้งค่าสไตล์ CSS ใน element

Signature:

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

Parameters:

Name Type Default Description
property string | string[] | Record<string, string> - ชื่อ CSS property, array หรือ object
value string | function - ค่า CSS ที่จะตั้งหรือฟังก์ชัน

Returns: string \| Record<string, string> \| Cheerio<T> - ค่า CSS หรือ Cheerio instance

Examples:

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

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

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

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

.addClass(className)

เพิ่ม CSS class ให้กับ element ที่ตรงกัน

Signature:

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

Parameters:

Name Type Default Description
className string | function - ชื่อคลาสที่คั่นด้วยเว้นวรรคหรือฟังก์ชัน

Returns: Cheerio<T> - Cheerio instance สำหรับการเชื่อมต่อ

Examples:

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

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

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

.removeClass(className?)

ลบ CSS class ออกจาก element ที่ตรงกัน

Signature:

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

Parameters:

Name Type Default Description
className string | function - คลาสที่จะลบ หรือฟังก์ชัน (ไม่ระบุเพื่อลบทั้งหมด)

Returns: Cheerio<T> - Cheerio instance สำหรับการเชื่อมต่อ

Examples:

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

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

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

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

.hasClass(className)

ตรวจสอบว่า element ที่ตรงกันใดๆ มี CSS class ที่ระบุหรือไม่

Signature:

function hasClass(className: string): boolean;

Parameters:

Name Type Default Description
className string - ชื่อคลาสที่จะตรวจสอบ

Returns: boolean - True ถ้า element ใดๆ มีคลาสนั้น

Examples:

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

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

Traversal and Filtering

.find(selector)

ค้นหา element ลูกหลานที่ตรงกับ selector

Signature:

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

Parameters:

Name Type Default Description
selector string - CSS selector ที่จะค้นหา

Returns: Cheerio<T> - คอลเลคชันของ element ลูกหลานที่พบ

Examples:

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

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

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

.each(callback)

วนซ้ำผ่าน element ที่ตรงกัน โดยเรียกใช้ callback สำหรับแต่ละอัน

Signature:

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

Parameters:

Name Type Default Description
callback function - ฟังก์ชันที่จะเรียกใช้สำหรับแต่ละ element

Returns: Cheerio<T> - Cheerio instance เดิม

Examples:

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

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

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

ข้อควรระวัง:

Form Handling

.serialize()

แปลง form element เป็น query string ที่เข้ารหัสแบบ URL

Signature:

function serialize(): string;

Returns: string - ข้อมูลฟอร์มที่เข้ารหัสแบบ URL

Examples:

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

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

.serializeArray()

แปลง form element เป็น array ของ object ที่มี name-value

Signature:

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

Returns: Array<{ name: string; value: string }> - Array ของ object ข้อมูลฟอร์ม

Examples:

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

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

ข้อควรระวัง: