Home > front end >  playwright select button by next element
playwright select button by next element

Time:12-12

<div >
   <button ></button>
   <div >James</div>
</div>
<div >
   <button ></button>
   <div >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?

CodePudding user response:

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 >
  <button >GOT IT</button>
  <div >James</div>
</div>
<div >
  <button ></button>
  <div >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.

  • Related