Search code examples
javascriptnode.jsfunctioncheerio

Cheerio: need to pass around $ along with elements?


I have several utitity functions, that operate on cheerio objects. To nearly every one of these functions I have to pass $ along with the element itsself.

Example:

function aUtilityFunc($, cheerioEl) { // <- $ in the params
    return cheerioEl.each(function (i, child) {
        // i do not want to do this:
        $(child).attr("something", $(child).attr("something") + "something");

        // i would rather do this and omit the $ in the params (like with global jquery doc):
        var $ = cheerioEl.$;
        $(child).attr("something", $(child).attr("something") + "something");
    });
}

Is there an elegant solution to this problem that would allow me to pass only 1 param to my functions? (I don't mean wrapping them into an object literal :>). Because frankly, it's not that nice this way (unless I'm overlooking something).


Solution

  • Seems like you could just do something like this:

    var $ = require('cheerio');
    
    function aUtilityMethod(cEls) {
        cEls.each(function(i, a) {
            console.log("li contains:", $(a).html());
        });
    }
    
    
    // testing utility method
    (function() {
        var fakeDocument = "<html><body><ol><li>one</li><li>two</li></ol></body></html>",
            myDoc = $(fakeDocument),
            myOl = $("ol", myDoc.html());
    
        aUtilityMethod(myOl.find("li"));
    })();