Probably easier...
Remove the first node matching selector
:
await page.$eval(selector, el => el.remove());
Remove all nodes matching selector
:
await page.$$eval(selector, els => els.forEach(el => el.remove()));
Wait for a selector, then remove it:
const el = await page.waitForSelector(selector);
await el.evaluate(el => el.remove());
If for some reason you need to select and remove in console browser-land:
const selector = ".foo";
// single
await page.evaluate(`
document.querySelector("${selector}").remove()
`);
// multiple
await page.evaluate(selector =>
document.querySelectorAll(selector).forEach(el => el.remove()),
selector
);
You can hardcode the selector into the eval
string/function as well but I figured it'd be useful to show it coming from a variable in two different ways just in case.
As with anything in Puppeteer, understanding which code runs in Node/Puppeteer-land and which code runs in browser/console-land is extremely important. The rule of thumb is: if it's a callback or stringified function body, it's in the browser and you can only use browser/DOM concepts like HTMLElement.remove()
, window
and document
, otherwise it runs in Node and you can only call Puppeteer API functions. In OP's case, it looks like we're outside of a callback in Node-land, so document
isn't a thing, only Puppeteer page.
functions.