I have an if statement below which is getting me an issue. If certain selections are made in a different dropdown, the page displays a second dropdown and a check box. The below code works as expected when a selection is made that causes those two elements to display but it doesn't if a selection is made that doesn't make them display. I get the no such element: Unable to locate element
error. At first I thought it was returning true either way but the issue is it's crashing because. I even added a check at trying to assign the value to a booolean but still get the same error.
boolean dropdown = driver.findElement(By.id("DROPDOWN")).isDisplayed();
gets the same error.
if(driver.findElement(By.id("DROPDOWN")).isDisplayed()){
driver.findElement(By.id("DROPDOWN")).click();
driver.findElement(By.xpath("Choice in Drop DOWN)).click();
driver.findElement(By.id("CheckBox")).click();
}
findElement method will throw this hard exception - No such element if the element is not found. Just include Exception Handling for No Such Element and your logic should work just fine.
try{
if(driver.findElement(By.id("DROPDOWN")).isDisplayed()){
driver.findElement(By.id("DROPDOWN")).click();
driver.findElement(By.xpath("Choice in Drop DOWN)).click();
driver.findElement(By.id("CheckBox")).click();
}
catch (NoSuchElementException e)
{
// I believe you dont have to do anything here. May be a console log will do.
}