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 = `
  <div>
    <h1>Header 1</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <h2>Header 2</h2>
    <p>Paragraph 3</p>
  </div>
`;

// 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: