How to check if element exists using Cypress.io - Stack Overflow

How to check if element exists using Cypress.io - Stack Overflow

Hey Neha Gupta,

Since Cypress commands are asynchronous, you should create a common function in your commands file or page object file to check Cypress if an element exists.

Here’s how you can structure it:

  1. Define the function to check if an element exists:

export function checkIfEleExists(ele) { return new Cypress.Promise((resolve, reject) => { cy.get(‘body’).find(ele).its(‘length’).then(res => { if (res > 0) { // Perform the task you want to if the element exists cy.get(ele).select(‘100’).wait(2000); resolve(); } else { reject(); } }); }); }

  1. Use the function to check for an element and handle the result: // Check if the element select[aria-label="rows per page"] exists cy.checkIfEleExists(‘select[aria-label=“rows per page”]’) .then(() => { // Perform actions if the element exists }) .catch(() => { // Perform actions if the element does not exist });

This approach ensures that you handle the asynchronous nature of Cypress commands effectively, using promises to manage the flow based on whether the element is present or not.

Hey Neha,

Here’s a solution you might find helpful:

You can use the following approach:

cy.window().then((win) => { const identifiedElement = win.document.querySelector(element); cy.log('Object value = ’ + identifiedElement); });

You can add this to your commands.js file in Cypress:

Cypress.Commands.add(‘isElementExist’, (element) => { cy.window().then((win) => { const identifiedElement = win.document.querySelector(element); cy.log('Object value = ’ + identifiedElement); }); });

This custom command checks if an element exists and logs its value.

Hey Nehagupta,

I encountered a similar issue where a button might appear on the webpage or not. I resolved it with the following code:

export function clickIfExist(element) { cy.get(‘body’).then((body) => { cy.wait(5000).then(() => { if (body.find(element).length > 0) { cy.log(‘Element found, proceeding with test’); cy.get(element).click(); } else { cy.log(‘Element not found, skipping test’); } }); }); }