I’m having trouble deleting HTML elements from a webpage using their class names in Puppeteer. When I run my script, the browser opens and takes a screenshot showing all the elements are still there, but my removal code doesn’t seem to work.
Here’s what I’m trying to do:
await page.screenshot({path: 'test-image.png'}); // checking if page loads
let element_class = ".btn.primary-btn";
var elementsFound = document.querySelectorAll(element_class);
var total_count = elementsFound.length;
for (var j = 0; j < total_count.length; j++) {
elementsFound[j].parentNode.removeChild(elementsFound);
}
The page loads fine and I can see all the target elements in my screenshot. But after running this code, nothing gets removed from the DOM. The elements with the specified classes are still visible on the page. What am I doing wrong here?
Your DOM manipulation code is running in Node.js instead of the browser - that’s the main problem. You need to wrap it with page.evaluate() so it executes inside the browser context.
Also spotted a couple bugs in your loop: you’re checking total_count.length when total_count is already a number, and you’re passing the entire NodeList to removeChild instead of the individual element.
I’ve hit these same issues when I started with Puppeteer. Here’s the fix:
This keeps your original approach but fixes the context issue and loop errors. page.evaluate() is essential whenever you need to interact with actual DOM elements.
yeah, wrap your code in page.evaluate() so it runs in the browser context. your loop’s broken too - you need elementsFound[j] in the removeChild line. try this instead: await page.evaluate(() => { const elements = document.querySelectorAll(‘.btn.primary-btn’); elements.forEach(el => el.remove()); });
Your DOM manipulation code isn’t running in the browser context. Puppeteer executes your JavaScript in Node.js, but DOM operations need to happen inside the browser. Use page.evaluate() to run the element removal code in the browser context. There’s also a bug in your loop - you’re using elementsFound[j] instead of elementsFound[j] in the removeChild call, and checking total_count.length instead of just total_count. Here’s the fix: javascript const elementsRemoved = await page.evaluate(() => { const elements = document.querySelectorAll('.btn.primary-btn'); elements.forEach(el => el.remove()); return elements.length; }); I’ve used this pattern tons of times in automation scripts. The remove() method is way cleaner than the parentNode approach, and forEach avoids those indexing errors.