Categories
JavaScript Answers

How to check if element exists using Cypress.io and JavaScript?

Spread the love

Sometimes, we want to check if element exists using Cypress.io and JavaScript.

In this article, we’ll look at how to check if element exists using Cypress.io and JavaScript.

How to check if element exists using Cypress.io and JavaScript?

To check if element exists using Cypress.io and JavaScript, we use the find method.

For instance, we write

const $body = await cy.get("body");
if ($body.find("button[data-cy=appDrawerOpener]").length > 0) {
  //...
}

to call the get method to get the body element.

Then we check if a button with data-cy attribute set to appDrawerOpener in the body element with $body.find.

If it returns length bigger than 0, then it’s found.

Conclusion

To check if element exists using Cypress.io and JavaScript, we use the find method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *