Search code examples
cssunit-testingselectorplaywright

playwright select button by next element


<div class="mysel">
   <button class="btn"></button>
   <div class="iconName">James</div>
</div>
<div class="mysel">
   <button class="btn"></button>
   <div class="iconName">John</div>
</div>

I want to click the button by codition of James so I try to use selector by this

 page.locator('button:right-of(:text("james")').click();

but fail how I could choice the button by txt in the next div?


Solution

  • There's not much context to work from here, and the -of selectors seem dependent on CSS/layout information I don't have, but selecting based on .mysel's text works for your example:

    const playwright = require("playwright"); // ^1.28.1
    
    const html = `
    <div class="mysel">
      <button class="btn">GOT IT</button>
      <div class="iconName">James</div>
    </div>
    <div class="mysel">
      <button class="btn"></button>
      <div class="iconName">John</div>
    </div>
    `;
    
    let browser;
    (async () => {
      browser = await playwright.chromium.launch();
      const page = await browser.newPage();
      await page.setContent(html);
      const sel = '.mysel:has(:text("james")) button';
      console.log(await page.locator(sel).textContent()); // => GOT IT
    })()
      .catch(err => console.error(err))
      .finally(() => browser?.close());
    

    '.mysel:has(.iconName:text("james")) .btn' is also possible in case there are other elements and you need to be more specific.