Technologies:
Tolerim
a month ago
What is the process for iterating through elements using a for loop in Puppeteer?
for (let i = 5; i <= 7; i++) {
const selector = `#div > div > div.view-setup-viewspopover-content > div > div:nth-child(${i}) > div > span`;
const dropdown_element = await page.$(selector);
// Select the three elements
await dropdown_element.focus();
await dropdown_element.click();
}
Answers(2)
Vogi
a month ago
Verified Answer
It looks like you're trying to iterate through elements in a for loop using Puppeteer. One possible reason why you're getting the error "Cannot read properties of null (reading 'focus')" is that the element you're trying to select doesn't exist on the page.
Here's an example of how you can iterate through elements in a for loop using Puppeteer:
for (let i = 5; i <= 7; i++) {
const selector = #div > div > div.view-setup-views__popover-content > div > div:nth-child(${i}) > div > span;
const dropdown_element = await page.$(selector);
if (dropdown_element) {
// Select the three elements
await dropdown_element.focus();
await dropdown_element.click();
}
}
This code checks if the element exists before attempting to select it. If the element doesn't exist, it will skip over it and continue iterating through the loop.
I hope this helps! Let me know if you have any other questions.Sources
https://stackoverflow.com/.../puppeteer-how-to-iterate-through-elements-in-a-for-loopTolerim
a month ago
The issue with your code is that you are using the escape sequence > instead of the > symbol to select the child elements. Also, you should wait for the elements to be visible on the page before trying to click on them. Here's an updated version of your code with these corrections:
const selectorPrefix = "#div > div > div.view-setup-views__popover-content > div > div:nth-child(";
const selectorSuffix = ") > div > span";
for (let i = 5; i <= 7; i++) {
const selector = selectorPrefix + i + selectorSuffix;
await page.waitForSelector(selector);
const dropdown_element = await page.$(selector);
// Select the three elements
await dropdown_element.focus();
await dropdown_element.click();
}
We first declare two variables, selectorPrefix and selectorSuffix, which will allow us to construct the selector for each element more easily. Then, we use a normal > symbol to select the child elements. We also added a waitForSelector call to make sure the element is visible on the page before trying to click on it.