🚀 We are hiring! See open positions

How to find HTML elements by text with Cheerio and NodeJS?

by Bernardas Alisauskas May 29, 2023 1 min read

Using NodeJS' Cheerio we can find any HTML element by partial or exact text value using the :contains() pseudo selector:

javascript
const cheerio = require('cheerio');

const $ = cheerio.load(`
    <a>ignore</a>
<a href="http://example.com">link</a>
<a>ignore</a>
`);
console.log(
    $('a:contains("link")').text()
);
"link"

This selector is case sensitive so it might be dangerous to use in web scraping. Instead, it's advised to filter values by text:

javascript
const cheerio = require('cheerio');

const $ = cheerio.load(`
    <a>ignore</a>
<a href="http://example.com">Link</a>
<a>ignore</a>
`);

console.log(
    $('a').filter(
        (i, element) => { return $(element).text().toLowerCase().includes("link")}
    ).text()
);
"link"
Scale Your Web Scraping
Anti-bot bypass, browser rendering, and rotating proxies — all in one API. Start with 1,000 free credits.
No credit card required 1,000 free API credits Anti-bot bypass included
Not ready? Get our newsletter instead.