How to find HTML elements by attribute using Cheerio?

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

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

const cheerio = require('cheerio');
const html = `
  <div data-example="1">This div has a data-example attribute with a value of 1</div>
  <div data-example="2">This div has a data-example attribute with a value of 2</div>
  <div>This div does not have a data-example attribute</div>
`;

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

// Find all div elements with a data-example attribute of "1" using the attribute selector
const divsWithAttribute = $('div[data-example="1"]');

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

// Output: 
// This div has a data-example attribute with a value of 1

Related Cheerio web scraping questions: