bernatfortet
bernatfortet

Reputation: 2312

Getting the sibling of an elementHandle in Puppeteer

I'm doing

const last = await page.$('.item:last-child')

Now I'd love to get the preceding element based on last. ie

const prev = last.$.prev()

Any thoughts on how to do this?

Thanks!

Upvotes: 16

Views: 14121

Answers (1)

Everettss
Everettss

Reputation: 16029

You should use previousElementSibling inside evaluateHandle, like this:

const prev = await page.evaluateHandle(el => el.previousElementSibling, last);

Here is full example:

const puppeteer = require('puppeteer');

const html = `
<html>
    <head></head>
    <body>
        <div>
            <div class="item">item 1</div>
            <div class="item">item 2</div>
            <div class="item">item 3</div>
        </div>
    </body>
</html>`;

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(`data:text/html,${html}`);

    const last = await page.$('.item:last-child');
    const prev = await page.evaluateHandle(el => el.previousElementSibling, last);

    console.log(await (await last.getProperty('innerHTML')).jsonValue()); // item 3
    console.log(await (await prev.getProperty('innerHTML')).jsonValue()); // item 2

    await browser.close();
})();

Upvotes: 20

Related Questions