Home » Jquery » javascript – Cheerio Closure Scope Behavior-Exceptionshub

javascript – Cheerio Closure Scope Behavior-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment


I’m using Cheerio (which is based on jQuery) to parse some HTML that I’ve scraped, but I’m unable to access the jQuery function (in this case, the $ sign) inside my each method.

Here’s the code that’s not working:

const function = $ => { // In this case, $ === cheerio.load(html)
    let res = [];
    let $items = $("div.recordsContainer table.recordList").first().find("tr").filter((i,v) => i > 0);
    $items.each((i,v) => {
      // I'm not able to access $ inside this function

Why am I unable to access the “$” variable inside the .each function?

The strange thing is, in many other cases in my code, this structure seems to work fine. What am I missing here?


Here you can see the cheerio variable ($) defined outside the map function. Why am I losing access to this variable inside the function?

enter image description here

How to&Answer: