I want to know how to check if an element exists in the DOM of a web page in Cypress.
What would the equivalent of this piece of code in Selenium be in Cypress:
Boolean Display = driver.findElement(By.xpath("locator")).isDisplayed();
I want to know how to check if an element exists in the DOM of a web page in Cypress.
What would the equivalent of this piece of code in Selenium be in Cypress:
Boolean Display = driver.findElement(By.xpath("locator")).isDisplayed();
Share
Improve this question
edited Jul 30, 2024 at 5:34
Sebold
1587 bronze badges
asked Mar 28, 2021 at 10:52
AmineAmine
9413 gold badges16 silver badges38 bronze badges
2 Answers
Reset to default 9To query with an xpath locator, install the cypress-xpath extension.
Install with npm
npm install -D cypress-xpath
Install with Yarn
yarn add cypress-xpath --dev
In the test
cy.xpath(locator) // driver.findElement(By.xpath("locator"))
Add a visibility check as well,
cy.xpath(locator) // driver.findElement(By.xpath("locator"))
.should('be.visible') // isDisplayed()
or
cy.xpath(locator) // driver.findElement(By.xpath("locator"))
.should('not.be.hidden') // isDisplayed()
1.To check element exists in the DOM:
cy.get(selector).should('exist')
2.To check that the element doesn't exist in DOM:
cy.get(selector).should('not.exist')
3.To check that element is visible:
cy.get(selector).should('be.visible')
4.To check that element is not visible:
cy.get(selector).should('not.be.visible')
5.Using JQuery:
cy.get('body').then(($body) => {
if ($body.find(selector).length > 0) {
//element exists do something
}
})