Royi Namir
Royi Namir

Reputation: 148524

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.

Upvotes: 20

Views: 10721

Answers (2)

Mir-Ismaili
Mir-Ismaili

Reputation: 16948

Use ElementHandle.evaluate():

const elementHandle = await page.waitForSelector('.selector-list li')

elementHandle.evaluate((domElement) => {
    domElement.tagName  
    // etc ...
})

Typescript:

const elementHandle: ElementHandle = await page.waitForSelector('.selector-list li')

elementHandle.evaluate((domElement) => {
    domElement.tagName  
    // etc ...
})

Upvotes: 9

Thomas Dondorf
Thomas Dondorf

Reputation: 25230

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.

Upvotes: 8

Related Questions