Skip to content

How to Get a Page Title with Cheerio

Cheerio parses an HTML string into a queryable structure.

OUTPUT FORMATSHTMLJSONMarkdown

To read the document title, load the HTML, select the title element, and call text(). This guide walks through the input, the selector, the extraction call, and the two distinct failure modes you should handle.

The core operation

Cheerio's title extraction is a two-step pattern: load the HTML string with cheerio.load(html), then run $('title').text(). The selector targets the title element; text() returns its text content. If the document has no title element, the selector matches nothing and text() returns an empty string rather than throwing.

Pipeline field map

The supplied code module shows a fetch → response.text() → cheerio.load → $('title').text() → console.log chain. Use this map to locate each stage:

  • Input: an HTML string from response.text().
  • Parser: cheerio.load(html) returns the $ query function.
  • Selector: 'title' targets the document title element.
  • Extraction: text() returns the element's text content.
  • Output: console.log prints the result.
  • Failure branch: the catch handler logs 'Failed to fetch page:' with the error.

Two failure modes to distinguish

A network or fetch failure rejects the promise and lands in the catch handler with the message 'Failed to fetch page:'. A missing title element is not an error: the selector returns an empty selection and text() yields an empty string. Check the returned value for emptiness if a missing title should be treated as a problem in your pipeline.

Checklist before running

  • Confirm the HTML string is the full document, not a fragment.
  • Confirm cheerio is installed and required.
  • Confirm the fetch target returns HTML rather than JSON.
  • Decide whether an empty title should be logged, skipped, or treated as a failure.
  • Keep the catch handler so network errors are visible.

Frequently asked questions

What does $('title').text() return if there is no title element?

It returns an empty string. The selector matches nothing and text() does not throw, so check for emptiness if a missing title matters to your pipeline.

Why does my catch handler fire?

The catch branch runs when the fetch promise rejects, for example on a network error. A missing title element does not trigger it.

Can I use a different selector for the title?

The title element is selected by its tag name, 'title'. If you need a different element, change the selector string accordingly.