Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

261
Vistas
How to make CONDITIONAL STATEMENTS using SELECTORS on PLAYWRIGHT?

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.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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*
about 4 years ago · Juan Pablo Isaza Denunciar

0

Since Playwright recommends using Locators over EventHandles (citation), you could also use:

async function clickIfNotNull(page, selector){
    const yourLocator = await page.locator(selector)
    const elementIsNotNull = await yourLocator.evaluate(elem => elem !== null);
    if (elementIsNotNull) {
        await yourLocator.click()
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Despite Playwright's recommendation around using Locators, if

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

Does the job fine, would this solution be ok to use?

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda