I’ll introduce sample code to get href values with cheerio, which can be used jQuery-like in Node.js.
- Official site: cheerio | Fast, flexible, and lean implementation of core jQuery designed specifically for the server.
- GitHub: cheeriojs/cheerio: Fast, flexible, and lean implementation of core jQuery designed specifically for the server.
❌ 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
- cheerio.load('<a href="foo"></a>').root().attr('href') gives undefined · Issue #994 · cheeriojs/cheerio
- Official site: cheerio | Fast, flexible, and lean implementation of core jQuery designed specifically for the server.
- GitHub: cheeriojs/cheerio: Fast, flexible, and lean implementation of core jQuery designed specifically for the server.