Deleting elements with specific class using Puppeteer

I’m trying to get rid of elements based on their class name but it’s not working. Here’s what I’ve got so far:

await page.capture('screenshot.jpg'); // just to check

const classToRemove = '.menu-item.dropdown';
const elementsToDelete = document.querySelectorAll(classToRemove);
const totalElements = elementsToDelete.length;

for (let i = 0; i < totalElements; i++) {
    elementsToDelete[i].remove();
}

The page loads fine and I can see everything in the screenshot. But after that, nothing changes. The elements I want to remove are still there. Any ideas what I’m doing wrong? I’m pretty new to Puppeteer so I might be missing something obvious.

I’ve encountered similar issues when working with Puppeteer. The problem here is that you’re trying to use document.querySelectorAll() in Node.js context, which doesn’t have access to the page’s DOM.

Instead, you need to execute this code within the browser context using page.evaluate(). Here’s how you can modify your code:

await page.evaluate(() => {
    const classToRemove = '.menu-item.dropdown';
    const elementsToDelete = document.querySelectorAll(classToRemove);
    elementsToDelete.forEach(el => el.remove());
});

This runs the code in the browser, where document is available. Also, I’ve simplified the loop using forEach for cleaner code. After running this, take another screenshot to confirm the elements are gone. Let me know if you need any further clarification!

hey, i thnk u are using document wrong in node.js. use page.evaluate() to run it in the browser. try: await page.evaluate(() => { document.querySelectorAll(‘.menu-item.dropdown’).forEach(el => el.remove()); }); hope this works, lmk if u need help!

I’ve run into this issue before. The key is to execute your DOM manipulation code within the page context. Try wrapping your code in page.evaluate() like this:

await page.evaluate(() => {
    const classToRemove = '.menu-item.dropdown';
    document.querySelectorAll(classToRemove).forEach(el => el.remove());
});

This ensures the code runs in the browser environment where document is accessible. After running this, take another screenshot to verify the elements are gone. If you’re still having trouble, double-check that your selector is correct and that the elements exist when the code runs. Timing can be tricky with dynamic content.