Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
Cheerio

How to Find HTML Elements by Class with Cheerio

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Load the HTML with cheerio.load(), then pass a class selector—one that starts with a period—to the returned $ function. For example, $('.intro') selects every element whose class list includes intro, regardless of its tag. Use $('p.intro') to restrict the results to paragraphs, or $('.post').find('.subtitle') to search only inside selected posts.

Load HTML before selecting elements

Cheerio selects from an HTML tree that you load into it; it does not open a URL or render a page in a browser as part of this basic selection step. The result of cheerio.load(markup) is the $ function used to query that loaded document.

import * as cheerio from 'cheerio';

const html = `
  <article>
    <p class="intro">Welcome</p>
    <p class="intro featured">Read this</p>
    <p>No intro class here</p>
  </article>
`;

const $ = cheerio.load(html);
const intros = $('.intro');

console.log(intros.length);          // 2
console.log(intros.first().text());  // Welcome

The key distinction is between the HTML string and the selection function: first load the markup, then query it. If your input comes from a file, an HTTP request, or another source, pass the resulting HTML string to cheerio.load() before selecting. This example uses a short inline string so that the selector’s behavior is easy to see.

Select by class, tag, and relationship

Cheerio uses CSS-selector syntax for selecting elements. A class selector begins with a period, and additional selector parts let you control which elements qualify and where they must occur.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Selector What it selects
$('.intro') Every element with the intro class, regardless of tag.
$('p.intro') Paragraph elements that have the intro class.
$('.intro.featured') Elements that have both the intro and featured classes.
$('h1, h2') Elements matching either the h1 selector or the h2 selector.
$('article .intro') Elements with class intro at any descendant depth inside an article.
$('article > .intro') Elements with class intro that are direct children of an article.

Use a period for a class, not a space

.intro means “has the class named intro.” In p.intro, the tag and class are adjacent selector parts: the element must be a paragraph and have that class. By contrast, article .intro contains a space. That space means the matching element must be a descendant of an article; it does not mean “an article with the intro class.” For the latter, write article.intro.

Require multiple classes when needed

The compound selector .intro.featured requires both classes on the same element. It does not match an element with only intro or only featured. This is useful when a class is common but a second class identifies the specific variant you want.

Choose descendant or direct-child scope

A descendant selector such as article .intro can match an element nested several levels below the article. The child combinator in article > .intro matches only immediate children. Choose the narrower relationship when the markup structure is part of what identifies the target, and the broader one when nested content should count too.

Scope searches to a selected container

Use .find() when you already have a selection and want matching descendants within it. It searches inside the current selection rather than starting over at the whole document.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const postSubtitles = $('.post').find('.subtitle');

For example, if the page contains several post containers, this selection returns their matching subtitle descendants. A document-wide $('.subtitle') can also match subtitles elsewhere on the page, outside any post. Scoping the search can make the intended relationship clearer and prevent unrelated matches from being included.

There are two other useful ways to narrow or exclude elements from an existing selection:

  • $('p').filter('.intro') keeps only paragraphs in the existing paragraph selection that match .intro.
  • $('p').not('.intro') keeps paragraphs that do not match .intro.

Use a direct selector such as $('p.intro') when it expresses the whole selection clearly. Use .filter() or .not() when you already have a set that you want to refine.

Read values from the matching elements

A selection is a Cheerio object wrapping the matched elements. Its length tells you how many elements matched. Methods such as .first(), .text(), and .attr() let you inspect results; .each() is useful when you need to process every match.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const $ = cheerio.load(`
  <ul>
    <li class="item"><a href="/one">First</a></li>
    <li class="item"><a href="/two">Second</a></li>
  </ul>
`);

const items = $('.item');
console.log(items.length); // 2

items.each((index, element) => {
  const item = $(element);
  console.log(index, item.text(), item.find('a').attr('href'));
});

Use .text() when you want the text contained by the selection, and .attr('href') when you want an attribute from an element. In the loop, wrapping the current element with $(element) gives you a selection on which to call Cheerio methods. If you only need the first match, $('.item').first() avoids iterating over the set.

Make selectors resilient to markup changes

Class names can be useful anchors, but a selector tied to a styling class may break if the site changes its presentation markup. Cheerio’s troubleshooting guidance recommends considering data attributes, element structure, or text matching with :contains() as alternative anchors when they better identify the content you need.

  • Use a data attribute when the markup exposes a stable identifier intended to describe an element’s role.
  • Use element structure when the relationship between a container and its contents is more dependable than a presentation class.
  • Use text matching when the text itself is the meaningful identifier and the selector is supported by your installed Cheerio version.

Do not make a selector more complex than necessary. A class-only selector is simple, but may be broad. A tag-plus-class or scoped search can reduce accidental matches. A selector that depends on many nested details may be more vulnerable if the source HTML changes. Inspect representative input and choose the narrowest selector that expresses the actual target reliably.

Understand what Cheerio does—and does not—select

Cheerio works on the parsed tree; it is not a browser renderer and does not apply CSS. Consequently, an element hidden visually by a stylesheet can still be present in the parsed HTML and match a selector. Conversely, content inserted only after browser-side JavaScript runs will not appear in the HTML string you loaded unless that content is already included in the input you provide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This matters when a selector appears to find something a visitor cannot see, or fails to find something visible after a page finishes loading. First inspect the markup passed to cheerio.load(). A selector can only match elements in that loaded tree. If you need to inspect a rendered page, obtain rendered HTML through a browser-based workflow before passing it to Cheerio; a CSS selector alone cannot cause Cheerio to render the page.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Selector support and pseudo-class errors

Cheerio supports most standard pseudo-classes and also documents extensions such as :contains() and positional selectors including :first, :last, and :eq(n). These positional extensions are not valid CSS selectors for browser use, so do not assume a selector that works in Cheerio can be copied unchanged into browser code.

If a pseudo-class produces an “Unknown pseudo-class” error, Cheerio’s troubleshooting guidance identifies the issue as an unsupported pseudo-class. That differs from a supported selector that returns an empty selection: in the latter case, the selector is understood, but nothing in the loaded tree matched it. Check the selector support for the Cheerio version installed in your project when behavior differs from the documentation-current guidance.

Troubleshoot an empty or unexpected selection

Symptom Likely cause What to check
The selection length is zero. The class or relationship does not occur in the loaded tree, or the selector is too restrictive. Inspect the input HTML, confirm the class spelling, and test a broader selector such as $('.intro') before adding tag or relationship constraints.
The selector matches too many elements. The class is used in multiple parts of the document. Add a tag condition, a second required class, or a container scope such as $('.post').find('.subtitle').
A visually hidden element is included. Cheerio selects from the tree and does not apply CSS visibility. Check the element’s markup and, if necessary, use information in the HTML to exclude it.
Content visible in a browser is missing. The supplied HTML may not include content added during browser-side rendering. Verify the exact string loaded by Cheerio; obtain rendered HTML through a browser workflow if the content is created after initial markup.
An “Unknown pseudo-class” error appears. The pseudo-class is not supported by the installed Cheerio selector implementation. Check Cheerio’s selector support and replace the pseudo-class with a supported selector or another traversal method.
A supported selector returns no matches. The selector is valid, but no element in the loaded tree satisfies it. Separate selector validity from input content: verify the class and structure in the markup, then relax the selector to identify which condition excludes the target.

Or skip the browser setup

Cheerio is the right fit when your task is to select and inspect HTML elements. If the task is instead to capture a clean screenshot or PDF of a URL, ScreenshotNeo can do that with a GET request; its screenshot API does not replace Cheerio’s DOM-selection methods.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://stripe.com 
  -o shot.webp

See the ScreenshotNeo API documentation for request options. It can accept cookie and consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture, with each step configurable. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; responses indicate the page verdict and billing status in headers. An MCP server offers take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients. The free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. Sign up for ScreenshotNeo’s free plan.

Frequently Asked Questions

Does $('.intro') select elements with more than one class?

Yes. An element matches if its class list includes intro, even if it has additional classes. Use $('.intro.featured') to require both named classes on the same element.

Does Cheerio select only elements visible in the browser?

No. It selects from the parsed HTML tree and does not apply CSS, so styling-based visibility does not determine whether an element matches.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.