Search code examples
playwrightplaywright-test

How to click the right button when there are two buttons with same text


There are two buttons both with Login as inner text

<div>
      <h3>
        Log in by Email
      </h3>
      <hr />
      Email: <input type="text" name="email"/>
      <button type="submit">
        Login
      </button>
      <h3>
        Log in by something else...
      </h3>
      <button type="submit">
        Login
      </button>
    </div>

I'm trying to click the login button next to the email input field

const login = await page.locator('button',{hasText:'Login'})
await login.click()

And it returns error:

locator.click: Error: strict mode violation: "button >> :scope:has-text("Login")" resolved to 2 elements:
        1) <button type="submit">Login</button> aka playwright.$("text=Login >> nth=1")
        2) <button type="submit">Login</button> aka playwright.$("text=Login >> nth=3")

I want to ask how can I locate the exact button while they both have the same text. Thank you


Solution

  • See if this works. You can select elements based on the layout.

    const btnLogin = await page.locator('button:has-text("Login"):near(input[name="email"])')
    await btnLogin.click()
    

    select button with text "Login" near input field with name "email"