📅  最后修改于: 2023-12-03 14:40:04.218000             🧑  作者: Mango
Cheerio is a fast and simple HTML parsing library for the Node.js environment. It provides a convenient way to traverse and manipulate HTML data using a jQuery-like syntax. One of the useful functions provided by Cheerio is each()
, which allows developers to iterate over a collection of elements.
To use Cheerio in your Node.js project, you need to install it using npm:
$ npm install cheerio
Import the Cheerio library in your JavaScript file:
const cheerio = require('cheerio');
Now, let's assume you have the following HTML code:
<ul id="fruits">
<li class="apple">Apple</li>
<li class="banana">Banana</li>
<li class="orange">Orange</li>
</ul>
To iterate over each <li>
element and perform a specific action, you can use the each()
function:
const $ = cheerio.load(html);
$('#fruits li').each((index, element) => {
const className = $(element).attr('class');
const text = $(element).text();
console.log(`Element at index ${index}: class='${className}', text='${text}'`);
});
The each()
function takes two parameters: index
and element
. The index
represents the index of the current element being iterated, while the element
represents the DOM element itself.
Within the callback function, you can use the $(element)
syntax to create a Cheerio object for the current element. This allows you to use various Cheerio methods, such as attr()
and text()
, to access and manipulate the element's attributes and text content.
In the above example, the output will be:
Element at index 0: class='apple', text='Apple'
Element at index 1: class='banana', text='Banana'
Element at index 2: class='orange', text='Orange'
This demonstrates how you can use Cheerio's each()
function to loop through a collection of elements and perform actions on each element individually.
For more information and advanced usage of Cheerio, refer to the official documentation.
Remember to mark down your code snippets using markdown syntax, like this:
const cheerio = require('cheerio');
const $ = cheerio.load(html);
$('#fruits li').each((index, element) => {
const className = $(element).attr('class');
const text = $(element).text();
console.log(`Element at index ${index}: class='${className}', text='${text}'`);
});
Happy parsing with Cheerio!