How to find HTML elements by class with Cheerio?

You can find HTML elements by class in Cheerio by using the class selector.

Here's some sample code that demonstrates how to find all div elements with a class of example using Cheerio:

const cheerio = require('cheerio');
const html = `
  <div class="example">This div has a class of example</div>
  <div class="example">This div also has a class of example</div>
  <div>This div does not have a class of example</div>
`;

// Load the HTML content into a Cheerio object
const $ = cheerio.load(html);

// Find all div elements with a class of "example" using the class selector
const divsWithClass = $('div.example');

// Iterate over each div element with a class of "example" and print its text content
divsWithClass.each((i, div) => {
    console.log($(div).text());
});

// Output: 
// This div has a class of example
// This div also has a class of example

Related Cheerio web scraping questions: