Search code examples
dompuppeteerdom-element

Converting an ElementHandle to a DOM element using puppeteer?


This is how I currently get each DOM property from an ElementHandle :

 let section: ElementHandle = await page.waitForSelector(".selector-list li");
 let tagName = await section.$eval('a', (e) => e.tagName);

But here it's tagName. What if I'd like want to inspect further properties ?

I don't want to write $eval for each property.

Question:

How can I convert ElementHandle to a Dom object , so I'd be able to browse all properties ? I want to get A as a Dom object.


Solution

  • The better way would be to execute the code on the page via page.evaluate and return the results. That way you can return an array with values:

    const result = await page.evaluate(() => {
        const elements = document.querySelectorAll(".selector-list li");
        // do something with elements, like mapping elements to an attribute:
        return Array.from(elements).map(element => element.tagName);
    });
    

    result will then be an array with the attribute values of tagName of each element.