2

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?

  • hi. interesting, you could convert it, but seems like it'd be quick to add the jquery https://stackoverflow.com/questions/46987516/inject-jquery-into-puppeteer-page – IronMan Feb 03 '21 at 00:48

2 Answers2

3

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

jbrtsnts
  • 76
  • 4
0

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

Renato
  • 121
  • 1
  • 8