In Puppeteer with Node.js, how can I retrieve a particular element using its position or matching text? For example:
const elements = await page.$$('.itemSelector');
const chosenElement = elements[1]; // alternatively, filter based on inner text
In Puppeteer with Node.js, how can I retrieve a particular element using its position or matching text? For example:
const elements = await page.$$('.itemSelector');
const chosenElement = elements[1]; // alternatively, filter based on inner text
Another method that worked well in my project was using page.$$eval to filter the list in the browser context. I filtered elements by checking their text content inside the page function. For example, you could use:
const chosenElement = await page.$$eval('.itemSelector', (elements, searchText) => {
return elements.find(el => el.textContent.trim() === searchText);
}, 'YourDesiredText');
This approach evaluates all nodes in the page and returns the one matching the exact text. It simplifies handling multiple elements and works reliably in complex DOM structures.
i’ve tried using page.evaluate to run document.querySelectorAll in the browser and filtering for the needed item by index or content. it allows direct manipulation of the elements array and works pretty well for smaller dom tasks, though error handlin might be needed sometimes.