DEV Community

KoichiArai
KoichiArai

Posted on

Day 23 of 100DaysOfCode

Hey! It's been a while since last entry.
Recently, I've been tackling an issue related to losing element references within a loop, and I finally found a solution that I'd like to share with you all.

What I wanted to achieve

  • Collect button elements on a specific webpage.
  • Click each buttons to navigate to another page.
  • After performing certain actions on the new page, go back to the first page.
  • Repeat Steps 2 and 3 until all buttons have been clicked.

Here's a simplified version of the initial code:

const someElements = await page.$$("xpath/ .//foo[@name='hoge']");

for (let i=0; i < someElements.length; i++) {
    await Promise.all([
        someElements[i].click(),
        page.waitForNavigation({ waitUntil: ["load", 'networkidle0'] }),
    /* There are particular processes and going back process */
    ]);
};
Enter fullscreen mode Exit fullscreen mode

What error I encountered

After the forst loop iteration, the script wasn't able to locate the button elements. I kept getting the following error:
ProtocolError: Protocol error (DOM.describeNode): Cannot find context with specified id at <instance_members_initializer>

How I solved it

I resolved this issue by re-declaring the button elements list within the loop.
Here's the modified code:

const someElements1 = await page.$$("xpath/ .//foo[@name='hoge']");

for (let i=0; i < someElements.length; i++) {
    const someElements2 = await page.$$("xpath/ .//foo[@name='hoge']"); // added row
    await Promise.all([
        someElements2[i].click(),
        page.waitForNavigation({ waitUntil: ["load", 'networkidle0'] }),
    /* There are particular processes and going back process */
    ]);
};
Enter fullscreen mode Exit fullscreen mode

I added re-declaration line because I assumed the original someElements reference was getting lost when navigating away from the initial page. After this change, the error was resolved. However, I'm not sure if this approach strictly adheres to best coding practices.

If you encounter an issue with .click() in a loop when navigating between pages, consider re-declaring the element within the loop itself. This simple change might save you a lot of troubleshooting time!

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay