Using .each to push items to array in Puppeteer

I would like to ask for help convert the following jQuery code into vanilla JS which is usable in Puppeteer.

var variants = [];
var stock;
$(".qty fieldset table tbody tr").each(function(index, ) {
    if (!$(this).find('td:eq(0) span').length && !$(this).find('td span a').length) {
        variants.push({
            color: $.trim($(this).find('td:eq(0)').text()),
            available: $(this).find('td:eq(1) span').data('tip').match(/\d+/)
        });
    } else if ($(this).find('td:eq(0) span').length && !$(this).find('td span a').length) {
        stock = $(this).find('td:eq(0) span').data('tip').match(/\d+/)
    }
});

var img = [];
if ($('.image-container').length > 0) {
    $(".image-container").each(function() {
        img.push({
            image: $(this).attr('href')
        });
    });
}

Or it would be better idea in this case to turn on jQuery in Puppeteer?

Upvotes: 2

Views: 255

Answers (2)

Renato
Renato

Reputation: 121

I was trying something like this some days ago, and It didn't worki with forEach (in javascript) try:

 for (item of itens) 

Don't know in Jquery, but in javascript .push inside forEach, doesn't work

Upvotes: 0

jbrtsnts
jbrtsnts

Reputation: 86

Yes you can inject jQuery using page.addScriptTag

...
await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'})
...

Documentation: page.addScriptTag

Upvotes: 3

Related Questions