I. using Element Handles within the condition
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
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*