How to select values between two nodes in Cheerio and Node.js?

You can select values between two nodes in
Cheerio
and Node.js by making use of a combination of the
nextUntil
and map methods to iterate over the elements between the two nodes and extract the desired values.

Here’s an example that demonstrates how to select values between two nodes in a simple HTML structure using Cheerio:

const cheerio = require('cheerio');
const html = `
  

Paragraph 1

Paragraph 2

Header 2

Paragraph 3

`; // Load the HTML content into a Cheerio object const $ = cheerio.load(html); // Select the first and second nodes using the CSS selector const startNode = $('h1'); const endNode = $('h2'); // Use the nextUntil method to select all elements between the start and end nodes const betweenNodes = startNode.nextUntil(endNode); // Use the map method to extract the text content of the elements const valuesBetweenNodes = betweenNodes.map((i, el) => $(el).text()).get(); // Print the selected values console.log(valuesBetweenNodes); // Output: // [ 'Paragraph 1', 'Paragraph 2' ]

Related Cheerio web scraping questions:

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *