I have multiple .home elements and I want to click on the last one

Here is what i wrote:

await page.waitForSelector('.home');
const el = await page.$eval('.home', (elements) => elements[elements.length - 1]);

But it does not work. Instead I get the following error:

TypeError: Cannot read property 'click' of undefined
    at open_tab (C:\wamp64\www\home_robot\robot.js:43:12)
    at process._tickCallback (internal/process/next_tick.js:68:

1 Answers

Thomas Dondorf On Best Solutions

The easiest way is to use page.$$ to get all element handles of the .home elements and then you click on the last element in the array:

const elements = await page.$$('.home');
await elements[elements.length - 1].click();

Why your code is not working

You cannot use page.$eval to return an element handle because the data you return there will be serialized via JSON.stringify when sending it from the browser to your Node.js environment.

Quote from the docs linked above:

returns: Promise<Serializable> Promise which resolves to the return value of pageFunction

As a DOM element cannot be serialized, you cannot click on it in your Node.js script and you get the error instead. You have to use page.$ or page.$$ to get the element handles.