Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cheerio returns undefined when calling .each() on elements

I want to make a request to website, get its html, and give it to cheerio. I need to get all the "href" attribute of all the elements with class ".thumb". I'm showing the results on the console and I just get undefined many times, I assume it's for each element found. I get undefined when trying to loop through any other element with tag or identifier, but if I don't loop and just get the first one the correct value is given.

  function firstReq(){
    req(url, (err,res,html)=>{
       if(err){console.error(err);}
       var $ = cheerio.load(html);
       var arr = []
       $("a").each(()=>{
         console.log($(this).attr("href"));
       });
    });
  }

I tried console.log(html) to check that the document was alright and it is. I also tried setting setTimeout on the iteration, maybe to give "request" and "cheerio" time to load the file, and still the same. I tried first downloading the html file from the url to my computer (outside of function, before call) and then passing it to cheerio, and still undefined.

It's my first personal project with Node and I'm very confused. Any help is appreciated.

like image 826
Josh M. Avatar asked Mar 19 '26 20:03

Josh M.


1 Answers

You can use two ways here:

Arrow function

function firstReq(){
   req(url, (err,res,html)=>{
     if(err){console.error(err);}
     var $ = cheerio.load(html);
     var arr = []
     $("a").each((i , elem)=>{
       console.log($(elem).attr("href"));
     });
   });
}

Or function:

function firstReq(){
   req(url, (err,res,html)=>{
     if(err){console.error(err);}
     var $ = cheerio.load(html);
     var arr = []
     $("a").each(function(){
       console.log($(this).attr("href"));
     });
   });
}
like image 88
Le Dinh Dam Avatar answered Mar 22 '26 10:03

Le Dinh Dam