[Node.js] Sample code to get href values with cheerio

Tadashi Shigeoka ·  Tue, December 25, 2018

I’ll introduce sample code to get href values with cheerio, which can be used jQuery-like in Node.js.

npm

❌ Incorrect cheerio sample code

Running the following code will output undefined.

const cheerio = require('cheerio');
const $ = cheerio.load('');
$().attr('href');

✅ Correct cheerio sample code

You need to explicitly run .find(‘a’) in the method chain and then get the href value with .attr(‘href’).

const cheerio = require('cheerio');
const $ = cheerio.load('');
$().find('a').attr('href');

That’s all from the Gemba where I was a bit confused about getting href values with cheerio.

Reference Information