Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer - Removing elements by class

I try to remove elements by classname but it doesn't work.

This is the code i used:

await page.screenshot({path: 'pic.png'});   //for testing purposes
    let div_selector_to_remove= ".xj7.Kwh5n";
    var thingToRemove = document.querySelectorAll(div_selector_to_remove);
    var number_of_elements = thingToRemove.length;
    for (var i = 0; i < number_of_elements.length; i++) {
        thingToRemove[i].parentNode.removeChild(thingToRemove);
    }

The browser loads and i get a screenshot with the elements loaded. The nothing happens. The elements remain there

like image 207
user1584421 Avatar asked Jun 14 '18 23:06

user1584421


People also ask

How do you destroy elements in DOM?

To remove an element from the DOM, you can also use the remove() method of the element. How it works. First, select the last element of the ul element. Second, call the remove() of that element to remove it from the DOM.

How do you delete an element in HTML?

Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.


1 Answers

Run document.querySelector inside page.evaluate. Here's my answer:

await page.goto('<url_here>');
let div_selector_to_remove= ".xj7.Kwh5n";
await page.evaluate((sel) => {
    var elements = document.querySelectorAll(sel);
    for(var i=0; i< elements.length; i++){
        elements[i].parentNode.removeChild(elements[i]);
    }
}, div_selector_to_remove)
like image 69
Tripti Rawat Avatar answered Oct 03 '22 13:10

Tripti Rawat