How to delete DOM elements using class selectors in Puppeteer

I’m having trouble with deleting specific elements from a webpage using their CSS class names in Puppeteer. When I run my script, the page loads correctly and I can see all elements in the screenshot, but the removal part isn’t working at all.

Here’s what I’m trying to do:

await browser.screenshot({path: 'test-image.png'});   // checking if page loads
let targetClass = ".nav-item.active";
var elementsFound = document.querySelectorAll(targetClass);
var totalCount = elementsFound.length;
for (var j = 0; j < totalCount.length; j++) {
    elementsFound[j].parentNode.removeChild(elementsFound);
}

The page renders fine and the screenshot shows everything loaded properly, but after running this code the elements I want to remove are still visible on the page. What am I doing wrong here?

The problem is you’re trying to run DOM manipulation in Node.js instead of in the browser. With Puppeteer, you need page.evaluate() to run JavaScript on the actual webpage. You’ve also got a couple bugs in your loop - you’re using totalCount.length instead of totalCount, and passing elementsFound instead of elementsFound[j] to removeChild(). Here’s the fix:

await page.evaluate(() => {
    let targetClass = ".nav-item.active";
    var elementsFound = document.querySelectorAll(targetClass);
    elementsFound.forEach(element => {
        element.parentNode.removeChild(element);
    });
});

This runs the code in the browser context where document exists. I used forEach to clean it up, but you could fix your original loop by correcting those variable names.

You can also use page.$$eval() which handles element selection and evaluation together. It’s built for running functions on multiple matching elements:

await page.$$eval('.nav-item.active', elements => {
    elements.forEach(el => el.remove());
});

I find this cleaner than page.evaluate() with querySelectorAll() since it handles selection automatically. remove() is more straightforward than parentNode.removeChild() and works well across browsers. Just take your screenshot after removing elements if you want to verify they’re gone - your current code screenshots before any DOM changes happen.

looks like you’ve got the main issue covered, but just wanted to add - if you’re still having trouble after using page.evaluate, check if the elements load dynamically. You might need await page.waitForSelector('.nav-item.active') before trying to remove them, especially with SPAs that load content async.