"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Day of DaysOfCode

Day of DaysOfCode

Published on 2024-10-31
Browse:665

Day of DaysOfCode

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 



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

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 



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!

Release Statement This article is reproduced at: https://dev.to/koichiarai/day-23-of-100daysofcode-2opg?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3