node.jscheerio

using cheerio, can't get attributes using .attr


Why do I have to use link.attribs.href instead of the standard .attr('href') method?

...
res.on('end', () => {
     const $ = cheerio.load(content);
     const link = $('.more-link').get(0);
     // const url = link.attr('href');   <--- link.attr is not a function
     const url = link.attribs.href;       <--- works
     console.log(url);
});

Solution

  • According to cheerio documentation, get(i) retrieves the "DOM" element from the cheerio instance you're working with. The cheerio instance object has an .attr() method, but the DOM element is just were they store that object data.

    You could use .first() instead of .get(0).