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!
You can get the elements by using the class in puppeteer, but the puppeteer does not understand what is class or id; so you have to use the CSS format to make the puppeteer understand it. Use . (dot) before the class name to denote that the following is class.
We can get element text in Puppeteer. This is done with the help of the textContent property. This property of the element is passed as a parameter to the getProperty method.
page. $eval() function is used to get the value for an element in puppeteer. $eval will stage two-parameter as an argument first parameter will be the selector and the second parameter will be element= element.
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();
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With