How to find sibling HTML nodes using Cheerio and NodeJS?

You can find sibling HTML nodes using
Cheerio
and Node.js by utilizing the siblings method of a Cheerio object.

Here’s some sample code that demonstrates how to find all sibling elements of a given element using Cheerio:

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

This is the first paragraph.

This is the second paragraph.

This is the third paragraph.

`; // Load the HTML content into a Cheerio object const $ = cheerio.load(html); // Select the second paragraph element const secondParagraph = $('p:nth-of-type(2)'); // Find all sibling elements of the second paragraph using the siblings method const siblingElements = secondParagraph.siblings(); // Iterate over each sibling element and print its text content siblingElements.each((i, element) => { console.log($(element).text()); }); // Output: // This is the first paragraph. // This is the third paragraph.

Note: p:nth-of-type(2) is used to select the second paragraph element. You can replace it with any other appropriate selector.

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 *