You can use all the testing and changing inside one page.evaluate()
:
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({ headless: false, defaultViewport: null });
const html = `
<!doctype html>
<html>
<head><meta charset='UTF-8'><title>Test</title></head>
<body>
<input type="checkbox" id="checkbox1"><label for="checkbox1">checkbox1</label><br>
<input type="checkbox" id="checkbox2" checked><label for="checkbox2">checkbox2</label><br>
<input type="checkbox" id="checkbox3" checked><label for="checkbox3">checkbox3</label><br>
<input type="checkbox" id="checkbox4"><label for="checkbox4">checkbox4</label><br>
</body>
</html>`;
try {
const [page] = await browser.pages();
await page.goto(`data:text/html,${html}`);
await page.evaluate(() => {
for (const checkbox of document.querySelectorAll('input')) {
if (!checkbox.checked) checkbox.click();
}
});
console.log('Done.');
} catch (err) { console.error(err); }
Or, if you need a loop over element handles, you can try this:
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({ headless: false, defaultViewport: null });
const html = `
<!doctype html>
<html>
<head><meta charset='UTF-8'><title>Test</title></head>
<body>
<input type="checkbox" id="checkbox1"><label for="checkbox1">checkbox1</label><br>
<input type="checkbox" id="checkbox2" checked><label for="checkbox2">checkbox2</label><br>
<input type="checkbox" id="checkbox3" checked><label for="checkbox3">checkbox3</label><br>
<input type="checkbox" id="checkbox4"><label for="checkbox4">checkbox4</label><br>
</body>
</html>`;
try {
const [page] = await browser.pages();
await page.goto(`data:text/html,${html}`);
for (const checkbox of await page.$$('input')) {
if (!await checkbox.evaluate(elem => elem.checked)) {
await checkbox.click();
}
}
console.log('Done.');
} catch (err) { console.error(err); }