Luxon
Installation
Install the Cheerio library:
npm install cheerio
Import
Import Cheerio into your project:
const cheerio = require('cheerio');
Load HTML
Load an HTML string into Cheerio:
const $ = cheerio.load('<html><head></head><body><h1>Hello, World!</h1></body></html>');
Selectors
Select an element by tag name:
const headings = $('h1');
Select an element by class:
const items = $('.item');
Select an element by ID:
const main = $('#main');
Select an element by attribute:
const links = $('a[href="https://example.com"]');
Traversing
Find child elements:
const listItems = $('ul').children();
Find a specific child element:
const firstListItem = $('ul').children().first();
Find parent element:
const parent = $('.item').parent();
Find the next sibling element:
const nextItem = $('.item').next();
Find the previous sibling element:
const prevItem = $('.item').prev();
Manipulation
Get an attribute value:
const href = $('a').attr('href');
Set an attribute value:
$('a').attr('href', 'https://new.example.com');
Get the text content of an element:
const text = $('h1').text();
Set the text content of an element:
$('h1').text('New Heading');
Get the HTML content of an element:
const innerHtml = $('div').html();
Set the HTML content of an element:
$('div').html('<p>New content</p>');
Remove an element:
$('.remove-me').remove();
Iteration
Iterate over elements using each
:
$('li').each((index, element) => {
console.log(index, $(element).text());
});
This cheat sheet provides a quick reference for using Cheerio in your Node.js projects.