1

How can I click on an outer element that contains a span with specific text via puppeteer?

For example I have the following HTML code:

<div role="button">
  <div>
    <span>
      <span>OK</span>
    </span>
  </div>
</div>

And I would like to click on the most outer element (role = button). In order to click on the span with the Ok text I would do the next thing:

const [button] = await page.$x("//span[contains(., 'Ok')]");
if (button) {
    await button.click();
}

But how can I click on the outer element using this text identifier?

Thomas Dondorf
  • 23,416
  • 6
  • 84
  • 105
user3710700
  • 301
  • 1
  • 4
  • 11

1 Answers1

0

You can use the descendant expression to query for child elements. Quote from the link:

The descendant axis indicates all of the children of the context node, and all of their children, and so forth.

Your XPath expression then looks like this:

//div[@role='button' and descendant::span[contains(., 'Ok')]]

Depending on your use case you might also want to check out this information about the difference of contains(text(), ...) and contains(., ...).

Thomas Dondorf
  • 23,416
  • 6
  • 84
  • 105