Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make CONDITIONAL STATEMENTS using SELECTORS on PLAYWRIGHT? [duplicate]

I need some help to make conditional statements using Playwright tests.
I have a given selector, let's say a button, and I need to write a conditional statement like this:

if (selector is not present/visible)

    do nothing and proceed with the *next lines of code*

else  

    await page.click(*selector*)

*next lines of code*

Is there any efficient way to do these kinds of things? I didn't found anything in the Playwright documentation.

like image 366
Ciccios_1518 Avatar asked Dec 04 '25 05:12

Ciccios_1518


1 Answers

UPDATE 2024: This answer originated in 2021 when Element Handles (approach I) was a more relevant concept in Playwright. As others pointed out: usage of Locators (approach II) is encouraged in current Playwright versions.


I. using Element Handles within the condition (DEPRECATED)

It can be implemented in JavaScript similarly to your pseudo-code using page.$(selector), which returns null if the specified element is not in the DOM. (Note: watch for the right usage of parenthesis inside the condition!)

I'd also reverse your initial if(falsy)...else condition into a single if(truthy), as you want to execute a command only if the selector exists, the else branch doesn't make too much sense:

if ((await page.$('#elem-id')) !== null) {
  await page.click('#elem-id')
}
// code goes on with *next lines of code*

II. using Locators within the condition (RECOMMENDED)

Some may notice the warning in the docs "The use of ElementHandle is discouraged, use Locator objects and web-first assertions instead." By default you shouldn't worry about using ElementHandles or mixing them together with Playwright's Locators in e2e tests or scrapers, they are inherited from Puppeteer and act reliably in Playwright as well (if they wouldn't: Microsoft would have deprecated them). Microsoft promotes Locators over Element Handles only because most of the extra functionalities they invested in in the past years (like "getByAltText", "getByLabel" etc.) are built on top of Locators so you can write e2e tests easier with their help. That's the reason for the warning in the docs. You don't need to avoid Element Handles at every cost.

If you want to reuse a locator in a conditional statement you can use locator.isVisible().

const myElement = page.locator('#elem-id') 
if (await myElement.isVisible()) {
  await myElement.click()
}
// code goes on with *next lines of code*
like image 84
theDavidBarton Avatar answered Dec 06 '25 17:12

theDavidBarton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!