cdbeelala89
cdbeelala89

Reputation: 2146

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).

Upvotes: 5

Views: 880

Answers (2)

ggorlen
ggorlen

Reputation: 56935

The existing answer doesn't work for me in Cheerio 1.0.0-rc.12. I don't see any obvious method in the current Cheerio version to do this.

My current workaround is to bind the $ to a closure:

const cheerio = require("cheerio"); // 1.0.0-rc.12

const bindCheerioHelpers = $ => ({
  textAll: s => [...$(s)].map(e => $(e).text().trim()),
});

const main = () => {
  const html = `<p>foo</p><p>bar</p>`;
  const $ = cheerio.load(html);
  const {textAll} = bindCheerioHelpers($);
  console.log(textAll("p")); // => [ 'foo', 'bar' ]
};
main();

I'd be happy to hear of a better way to do it. Maybe I'm missing something obvious.

Upvotes: 0

Jack
Jack

Reputation: 21163

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"));
})();

Upvotes: 4

Related Questions