How to get ElementHandle based on `innerText`?

2k Views Asked by At

I have a list of links, and want to click on one of them based on the name of the link. I can't accomplish this with selectors.

It would be nice to use something like page.$eval to get the ElementHandle of that item so I can then tap/click it.

The only other approach I can think of is getting the x/y coords within $eval and then manually clicking on clicking on the location. Seems tedious.

I posted this here per the guidelines, but LMK if we should open a PR on this.

1

There are 1 best solutions below

0
On

Have you considered use the page.$$(selector) to get all your target elments and then use page.evaluate() to get the linkName, then do the check and click?

something like:

const targetLinks = await page.$$('yourLinkSelector');
for(let link of targetLinks){
  const linkName = await page.evaluate(el => el.innerHTML, link); 
  if (linkName === 'myFancyLinkToClick') {
    await link.click();
    // break if only 1 link click is needed.
    break;
  }
}

Hope it works for you.