While writing end-to-end tests with Cypress, one basic need is to check whether a specific element exists on the page before interacting with it. Cypress provides powerful and interactive commands like .should(‘exist’), .should(‘not.exist’), and conditional checks to verify the presence or absence of elements in the DOM. This is useful for testing dynamic UIs, conditional rendering, or validating user flows based on element visibility.
Read this guide to learn more about the Cypress check if elements exists, the process of using it, and more.
What are Cypress Elements?
In web applications, elements refer to the individual HTML elements that make up the structure and content of a web page. These elements include buttons, text boxes, links, images, etc. Each element has its attributes, such as id, class, and style, that can be used to select it and interact with CSS or JavaScript selectors.
- Elements are an important part of web applications, as they define the structure and behavior of a page.
- By selecting and interacting with elements, you can write automated tests to verify that the web application behaves as expected for all users.
- In Cypress, elements refer to the HTML elements of your website that you want to interact with or test.
- To interact with or test these elements, select them with a selector, like in CSS.
Also Read: Cypress Locators : How to find HTML elements
Why Element Existence Matters in Cypress?
Modern web applications use dynamic content, conditional rendering, and asynchronous behavior, which means elements might not always be present at the time the test is executed. Validating the existence of elements helps to analyze real user experiences and prevents false positives or test issues.
Some of the key reasons why element existence matters are:
- Validates Dynamic Content Rendering: Many web apps load content based on user interaction or API responses. Checking the existence of elements helps confirm that content loads as expected.
- Prevents Test Failures on Conditional Elements: Checking the existence of the conditional UI components helps to interact with elements that might not be rendered.
- Improves Test Stability and Reliability: Explicitly confirming an element’s existence helps to start interaction only when the elements are ready.
- Improves User Flow Validation: Checking for expected elements like buttons, links, or success messages confirms the correct path of user functioning.
Benefits of using the Cypress Check if Element Exists Command
The “Check if element exists” command in Cypress has several advantages:
- Improved test reliability
- Improved readability of tests
- Improved Test Maintainability
- Improved debugging
Syntax for the check if element exists command
- Cypress provides the. should(‘exist’) and. should (‘not. Exist’) commands to determine if an element exists on a page.
- These commands provide a convenient alternative to using a. then () and checks the element’s. length property, providing a more concise and readable syntax for this type of assertion.
- The “Cypress test element does exist” command is used to verify that a specific element exists on a web page.
- In Cypress, you can use the “.exists()” method to check if an element exists. This method returns a boolean value, indicating whether the element exists.
Here’s an example of how you might use the “Cypress test element does exist” command:
cy.get('#element-id').should('exist');
In this example,
- “. get()” method is used to target the element with the ID of “element-id”.
- “. should()” method is then used to assert the element, in this case, that it exists.
If the element does not exist, the test will fail and return an error message indicating that the element was not found. You can also use the “.should(‘not.exist’)” method to verify that an element does not exist on a page.
cy.get('#element-id').should('not.exist')
In this example,
- cy.get(‘#element-id’) method is used to retrieve the element with the id of ‘element-id’.
- .should(‘not.exist’) command is then used to assert that the element does not exist on the page.
If the element does not exist, the test will pass. If the element does exist, the test will fail, and an error will be displayed in the Cypress test runner.
Use case scenarios for check if element exists command
Here are a few use case scenarios for the “check if element exists” command in Cypress:
- Verifying the existence of a critical element on a page
- Validating the display of an element after an action
- Testing element visibility and accessibility
- Debugging failing tests
How are Cypress elements used in web applications?
Cypress elements simulate user interactions and test application behavior in a web application. You can write tests that simulate real user interactions with your application by selecting elements on the page using selectors and interacting with them using Cypress commands.
Here is a simple example showing how Cypress elements can be used in a web application:
Step 1
cy.visit('https://example.com/login');
This example uses the cy.visit() command to load the web application login page.
Step 2
cy.get('#username').type('user@example.com'); cy.get('#password').type('password');
Then the cy.get() command is used to select the username and password input fields and the .type() method is used to fill in the values.
Step 3
cy.get('#submit-button').click(); cy.contains('Login successful');
Finally, click the Submit button and use the cy.contains() command to see if the text “Connection successful” appeared on the page.
How to Verify the Existence of an Element Using Cypress?
There are several ways to verify the existence of an element using Cypress, such as:
1. Using .should(‘exist’)
This is one of the simplest ways to check that an element is present in DOM. This tells Cypress to wait for the element and confirm its existence. If the element is not found within the default timeout, the test will fail.
cy.get('.login-button').should('exist');
Cypress automatically retries the cy.get() command until the element exists or the timeout is reached. This implicit retry behavior helps prevent short tests from occurring due to minor delays in rendering.
2. Using .should(‘not.exist’)
To confirm that an element is not present in the DOM (e.g., verifying a loading spinner, or if an error message disappears), use this syntax:
cy.get('.error-message').should('not.exist');
This is mainly useful when validating UI changes. For example, after correcting form input, a user might expect an error message to disappear. Cypress will automatically retry the assertion until the element is removed or the timeout is reached, helping to prevent flaky tests caused by irregular UI updates.
3. Conditional Check Using .then()
To check any particular element’s existence, use .then() with jQuery’s .find() method:
cy.get('body').then(($body) => { if ($body.find('.popup-modal').length > 0) { cy.get('.popup-modal .close-btn').click(); } });
4. Verifying Visibility and Existence Together
To check both the visibility and existence of an element together in the DOM, use an assertion like this:
cy.get('.notification').should('exist').and('be.visible');
While .be.visible confirms that the element is rendered and not hidden via CSS, it doesn’t guarantee that the element is interactable. If elements like buttons or inputs are tested, consider adding .and(‘not.be.disabled’) to confirm they are usable as well.
Read More: Conditional Testing in Cypress: Tutorial
Cypress Check if Element Exists Command
While Cypress doesn’t have a built-in command like cy.elementExists(), users can implement this behavior using native Cypress commands such as .get() combined with assertions like .should(‘exist’), or by using conditional logic with .then() and .find(). This helps to verify that an element is present in the DOM before interacting with it, preventing unnecessary test failures and maintaining test accuracy.
Explanation of the check if element exists command
Cypress provides several ways to verify that an element is present on a page. You can use the cy.get() method to get an element and check its length to see if it exists.
Here is an example:
cy.get('#element-id').then(($el) => { if ($el.length) { // Element exists, do something } else { // Element does not exist, do something else } });
You can also use the cy.contains() method to search for elements that contain a specific text and check the length of the returned elements to see if there are any:
cy.contains('Text of element to search for').then(($el) => { if ($el.length) { // Element exists, do something } else { // Element does not exist, do something else } });
If you just need to know if an element exists and you don’t need to interact with it, you can use the cy.get() method with .should(‘exist’) or .should(‘not.exist’ ) .
Commands:
cy.get('#element-id').should('exist'); cy.get('#element-id').should('not.exist');
How to Use the Cypress Check if Element Exists Command [with Example]
Here’s a Step-by-step process to check if an element exists in Cypress:
Step 1. Load the page: Use the cy.visit command to load the page you want to test.
For example:
cy.visit('http://localhost:3000/index.html')
Step 2. Select the element: Use the cy.get command to select the element you want to check if it exists.
For example, if you want to check if an element with the ID “header” exists:
cy.get('#header')
Step 3. Make the assertion: Use the .should(‘exist’) command to make an assertion that the element exists on the page. For example:
cy.get('#header').should('exist')
Step 4. Run the test: Run the test in the Cypress Test Runner to see if the element exists.
How to Check for an Element that May Not Exist Using Cypress?
Here are some of the important steps to be followed for checking an element that may not exist using Cypress:
Step 1: Use cy.get() with { timeout: 0 } to prevent retries
Since the element may not appear at all, there’s no need for retrying using Cypress.
cy.get('.optional-banner', { timeout: 0 }).should('not.exist');
Step 2: Use conditional logic with .then() and jQuery .find()
This allows to check the presence of the element and decide what to do next.
cy.get('body').then(($body) => { if ($body.find('.optional-banner').length) { cy.get('.optional-banner').click(); } else { cy.log('Optional banner not found'); } });
Step 3: Wrap conditionals in reusable functions
For better test logic, wrap this in a custom Cypress command.
Read More: How to Scroll to Element in Playwright
How to Check if an Element Exists in Cypress for Interaction?
Before interacting with an element, confirm that the element exists and is visible to avoid incorrect tests.
Step 1: Target the element using cy.get()
cy.get('.submit-button').should('exist');
Step 2: Chain .should(‘be.visible’) to confirm it’s interactable
cy.get('.submit-button').should('exist').and('be.visible');
Step 3: Perform the interaction
cy.get('.submit-button').should('exist').and('be.visible').click();
Step 4: Handle conditionally displayed buttons
cy.get('body').then(($body) => { if ($body.find('.submit-button').length) { cy.get('.submit-button').click(); } });
Read More: How to Inspect Element in Chrome
How to Check if an Element Exists in Cypress Over the Cloud?
While running tests in clouds like BrowserStack, checking element existence is still done using Cypress commands like .should(‘exist’) or .then(). However, a few cloud-specific conditions may affect the reliability of these checks.
These include network latency, slower DOM rendering times due to virtualization, and limited debugging visibility compared to local runs.
To resolve this, use increased timeouts through Cypress’s built-in retry ability, and allow for video or screenshot capture whenever the test fails.
Step 1: Use standard Cypress existence checks
cy.get('.dashboard-card').should('exist');
Step 2: Log useful messages for CI visibility
cy.get('body').then(($body) => { if ($body.find('.dashboard-card').length) { cy.log('Element found — test continues'); } else { cy.log('Element not found — skipping click'); } });
Step 3: Check for Browser Compatibility with real-device testing
To ensure elements render properly across devices, use BrowserStack’s Cypress integration to test on real browsers and operating systems.
How to Verify Element Visibility [if Hidden] Before Clicking Without Failing the Test?
Sometimes an element is present in the DOM but hidden. Here are the steps to be followed for verifying element visibility before clicking:
Step 1: Check if the element exists
Here’s how you can check if the element exists:
cy.get('body').then(($body) => { if ($body.find('.menu-toggle').length) { const toggle = $body.find('.menu-toggle');
Step 2: Check if it’s visible before interacting
Here’s an example to check if the element is visible before interacting:
if (Cypress.$(toggle).is(':visible')) { cy.wrap(toggle).click(); } else { cy.log('Element is hidden, skipping click'); } } });
Step 3: Combine everything in one logic block
To prevent the tests from failing due to hidden elements, combine existence and visibility checks in a single, readable logic block. In this manner, the test can conditionally interact with the element only when it’s safe to do so, and log useful feedback.
Here’s how to structure the complete logic:
cy.get('body').then(($body) => { if ($body.find('.menu-toggle').length) { const toggle = $body.find('.menu-toggle'); if (Cypress.$(toggle).is(':visible')) { cy.wrap(toggle).click(); } else { cy.log('Element exists but is hidden - skipping click.'); } } else { cy.log('Element does not exist in the DOM.'); } });
Conditional Testing in Cypress [With Example]
Conditional testing allows us to write test logic that checks the presence or absence of elements, to make the tests more flexible, accurate, and resilient. The foundation of conditional testing often starts with checking if an element exists.
Before interacting with or asserting on an element, Cypress verifies its presence in the DOM using standard DOM querying and jQuery-based logic inside .then().
Cypress doesn’t have built-in if-else control flows at the command level because Cypress commands are asynchronous. Instead, it uses .then() to run synchronous checks using the jQuery-wrapped DOM.
Example: Conditionally Clicking a Button Only If It Exists
cy.get('body').then(($body) => { if ($body.find('.subscribe-btn').length > 0) { cy.get('.subscribe-btn').click(); } else { cy.log('Subscribe button not found, skipping click.'); } });
Read More: Understanding Testing Library Jest DOM
Running Cypress Tests on BrowserStack
Running your Cypress Tests on BrowserStack allows to execute them easily across a wide range of real browsers, operating systems, and devices. With built-in support for Cypress through its Automate platform, BrowserStack offers a scalable, secure, and efficient way to run your end-to-end tests at speed and scale.
Key Features of BrowserStack Automate
Here are some of the key features of BrowserStack Automate tool:
- Real Browsers and Devices in Cloud: Run Cypress tests on 3,500+ combinations of real browsers and devices with zero setup or VMs.
- Parallel Execution: Automate supports parallel testing in Cypress, helping teams reduce test runtime and accelerate feedback loops.
- CI/CD Integrations: Easily integrate with tools like GitHub Actions, Jenkins, CircleCI, GitLab CI, and more to simplify Cypress testing.
- Advanced Debugging Insights: Get video recordings, screenshots, console logs, and network logs for every test run to identify the failures.
- Cross-Browser Testing: Unlike local environments limited to a single browser, Automate tests across Chrome, Firefox, Safari, Edge, and more.
Real-World Applications of Element Existence Checks
Some of the real-world applications of element existence checks are:
- Conditional Popups & Modals: Handle modals or popups that appear only under certain conditions (Example: For first-time users, promotions).
- Authentication Flow Validation: Ensure login or logout buttons appear or disappear based on the user’s authentication state.
- Error and Alert Messages: Confirm the appearance of validation errors, toast messages, or alerts when expected and ensure that they’re removed once resolved.
- Dynamic UI Components: Detect the presence of dynamically loaded components like lazy-loaded widgets or third-party embeds.
Read More: How to test UI components?
Conclusion
Element existence checks in Cypress are important for building reliable, adaptable test suites that handle dynamic and conditional UI elements effectively. They help prevent test failures, and support responsive and role-based design testing.
By following some of the best practices like conditional logic and visibility checks, and relying on scalable platforms like BrowserStack Automate, you can enable fast, and stable cross-browser and Cypress test execution.
Frequently Asked Questions
- How do you check if a list element exists?
To check if a list element exists, use cy.get() with a selector targeting the list item, followed by .should(‘exist’).
For example:
cy.get('ul li').should('exist');
For checking a specific list item with a certain text:
cy.get('ul li').contains('Item Name').should('exist');
- How to check if element has text in Cypress?
Check if an element contains specific text using .should(‘contain’, ‘Your Text’) or .should(‘have.text’, ‘Exact Text’).
cy.get('.message-box').should('contain', 'Success');
For an exact match (no extra whitespace or formatting):
cy.get('.message-box').should('have.text', 'Success');