Referensi API Cheerio
Cheerio adalah implementasi server-side dari fungsionalitas inti jQuery yang cepat, fleksibel, dan elegan. Cheerio menyediakan API mirip jQuery yang familiar untuk parsing dan memanipulasi dokumen HTML dan XML di lingkungan Node.js.
Fungsi Loading Inti
cheerio.load(content, options?)
Memuat konten HTML/XML dan mengembalikan instance CheerioAPI untuk query dan manipulasi.
Signature:
function load(
content: string | AnyNode | AnyNode[] | Buffer,
options?: CheerioOptions,
isDocument?: boolean
): CheerioAPI
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
content |
string | AnyNode | AnyNode[] | Buffer |
- | Konten HTML/XML yang akan di-parse |
options |
CheerioOptions |
{} |
Opsi parser dan behavior |
isDocument |
boolean |
true |
Apakah konten diperlakukan sebagai dokumen lengkap |
Returns: CheerioAPI - Instance Cheerio dengan method mirip 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);
Common gotchas:
- Mode XML harus diaktifkan secara eksplisit untuk dokumen XML
- Secara default, aturan parser HTML5 berlaku (self-closing tag, dll.)
- Encoding Buffer terdeteksi otomatis namun mungkin perlu spesifikasi eksplisit
Seleksi Element
$(selector, context?, root?)
Memilih element dari dokumen yang dimuat menggunakan CSS selector, mirip dengan fungsi $() jQuery.
Signature:
function $(
selector: string | AnyNode | AnyNode[] | Cheerio<AnyNode>,
context?: string | AnyNode | Cheerio<AnyNode>,
root?: string | Document
): Cheerio<Element>
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
selector |
string | AnyNode | AnyNode[] | Cheerio<AnyNode> |
- | CSS selector atau element yang akan dipilih |
context |
string | AnyNode | Cheerio<AnyNode> |
document |
Konteks untuk pencarian |
root |
string | Document |
- | Dokumen root untuk konteks |
Returns: Cheerio<Element> - Koleksi element yang cocok
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
Manipulasi Attribute
.attr(name, value?)
Mengambil atau mengatur attribute pada element yang cocok.
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:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
name |
string | Record<string, string | null> |
- | Nama attribute atau object map |
value |
string | null | function |
- | Nilai yang akan diset, null untuk menghapus, atau function |
Returns: string \| undefined \| Cheerio<T> - Nilai attribute (getter) atau instance Cheerio (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://'));
Common gotchas:
- Mengatur attribute ke
nullakan menghapusnya sepenuhnya - Boolean attribute mengembalikan nama mereka ketika ada (
'checked'), bukantrue - Function menerima index dan nilai saat ini sebagai parameter
.prop(name, value?)
Mengambil atau mengatur property pada element DOM, menangani property khusus seperti checked, selected, dll.
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:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
name |
string | Record<string, any> |
- | Nama property atau object map |
value |
any |
- | Nilai yang akan diset |
Returns: any \| Cheerio<T> - Nilai property (getter) atau instance Cheerio (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?)
Mengambil atau mengatur data attribute dengan konversi tipe otomatis untuk attribute data-* 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>;
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
key |
string | Record<string, unknown> |
- | Key data atau object map |
value |
unknown |
- | Nilai yang akan diset |
Returns: unknown \| Record<string, unknown> \| Cheerio<T> - Nilai data atau instance Cheerio
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"
Common gotchas:
- Data attribute secara otomatis di-parse (JSON, number, boolean)
- Key camelCase dipetakan ke data attribute dengan tanda hubung
- Data yang diset melalui
.data()tidak mengupdate attribute HTML aktual
Manipulasi Konten
.text(value?)
Mengambil atau mengatur konten teks dari element, menghilangkan semua tag HTML.
Signature:
// Get text
function text(): string;
// Set text
function text(value: string | number | ((i: number, text: string) => string | number)): Cheerio<T>;
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
value |
string | number | function |
- | Konten teks yang akan diset atau function |
Returns: string \| Cheerio<T> - Konten teks (getter) atau instance Cheerio (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?)
Mengambil atau mengatur konten inner HTML dari element.
Signature:
// Get HTML
function html(): string | null;
// Set HTML
function html(value: string | ((i: number, html: string) => string)): Cheerio<T>;
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
value |
string | function |
- | Konten HTML yang akan diset atau function |
Returns: string \| null \| Cheerio<T> - Konten HTML (getter) atau instance Cheerio (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}`);
Common gotchas:
.html()mengembalikan inner HTML, gunakan.prop('outerHTML')untuk element lengkap- Mengatur HTML akan menimpa semua konten yang ada
- HTML tidak disanitasi - hati-hati dengan input user
.val(value?)
Mengambil atau mengatur nilai dari element form (input, select, textarea).
Signature:
// Get value
function val(): string | string[] | undefined;
// Set value
function val(value: string | string[]): Cheerio<T>;
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
value |
string | string[] |
- | Nilai yang akan diset (array untuk multi-select) |
Returns: string \| string[] \| undefined \| Cheerio<T> - Nilai form atau instance Cheerio
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...');
Manipulasi DOM
.append(content)
Menyisipkan konten sebagai child terakhir dari setiap element yang cocok.
Signature:
function append(
...contents: (
| string
| AnyNode
| AnyNode[]
| Cheerio<AnyNode>
| ((i: number, html: string) => string | AnyNode | Cheerio<AnyNode>)
)[]
): Cheerio<T>;
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
contents |
string | AnyNode | Cheerio | function |
- | Konten yang akan ditambahkan |
Returns: Cheerio<T> - Instance Cheerio asli
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?)
Menghapus element yang cocok dari DOM.
Signature:
function remove(selector?: string): Cheerio<T>;
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
selector |
string |
- | Selector opsional untuk memfilter penghapusan |
Returns: Cheerio<T> - Element yang dihapus
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 dan Styling
.css(property, value?)
Mengambil atau mengatur style CSS pada 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:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
property |
string | string[] | Record<string, string> |
- | Nama property CSS, array, atau object |
value |
string | function |
- | Nilai CSS yang akan diset atau function |
Returns: string \| Record<string, string> \| Cheerio<T> - Nilai CSS atau instance Cheerio
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)
Menambahkan class CSS ke element yang cocok.
Signature:
function addClass(
className: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
className |
string | function |
- | Nama class yang dipisahkan spasi atau function |
Returns: Cheerio<T> - Instance Cheerio untuk chaining
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?)
Menghapus class CSS dari element yang cocok.
Signature:
function removeClass(
className?: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
className |
string | function |
- | Class yang akan dihapus, atau function (abaikan untuk menghapus semua) |
Returns: Cheerio<T> - Instance Cheerio untuk chaining
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)
Mengecek apakah ada element yang cocok memiliki class CSS yang ditentukan.
Signature:
function hasClass(className: string): boolean;
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
className |
string |
- | Nama class yang akan dicek |
Returns: boolean - True jika ada element yang memiliki class tersebut
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 dan Filtering
.find(selector)
Mencari element descendant yang cocok dengan selector.
Signature:
function find<T extends AnyNode>(selector: string): Cheerio<T>;
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
selector |
string |
- | CSS selector untuk pencarian |
Returns: Cheerio<T> - Koleksi element descendant yang ditemukan
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)
Melakukan iterasi pada element yang cocok, menjalankan callback untuk setiap element.
Signature:
function each(
callback: (this: T, i: number, el: T) => void | false
): Cheerio<T>;
Parameters:
| Nama | Tipe | Default | Deskripsi |
|---|---|---|---|
callback |
function |
- | Function yang akan dijalankan untuk setiap element |
Returns: Cheerio<T> - Instance Cheerio asli
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}`);
});
Common gotchas:
- Return
falsedari callback untuk menghentikan loop lebih awal - Arrow function tidak mengikat
thiske element saat ini - Parameter index dimulai dari nol
Penanganan Form
.serialize()
Melakukan serialisasi element form menjadi query string yang di-encode URL.
Signature:
function serialize(): string;
Returns: string - Data form yang di-encode 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()
Melakukan serialisasi element form menjadi array dari object name-value.
Signature:
function serializeArray(): Array<{ name: string; value: string }>;
Returns: Array<{ name: string; value: string }> - Array dari object data form
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;
});
Common gotchas:
- Hanya form control yang berhasil yang diserialisasi
- Element yang disabled diabaikan
- Checkbox/radio harus dicentang untuk disertakan
- Input file mengembalikan filename, bukan konten file