Reputation: 4318
public boolean addNewAlertIsDisplayed() {
if(driver.findElement(By.xpath("//*[@class='aside right am-slide-right']")).isDisplayed()) {
return true;
}
else {
return false;
}
}
I am expecting false if it is not there..
But getting:
org.openqa.selenium.NoSuchElementException: Unable to find element with xpath == //*[@class='aside right am-slide-right'] (WARNING: The server did not provide any stacktrace information)
Why this exception is coming.. Is this needs to be handled in try/catch?
Upvotes: 1
Views: 489
Reputation: 5637
Try this:
public boolean addNewAlertIsDisplayed() {
List<WebElement> elements = driver.findElements(By.xpath("//*[@class='aside right am-slide-right']"));
return elements.size() > 0 && elements.get(0).isDisplayed();
}
If there are no elements it won't throw any exception. It will just be a list of size 0. Also as @Corey Goldberg mentioned, there should be checked if this element actually displayed. I forgot to add this to method.
Upvotes: 1
Reputation: 2334
Please check and use any one of the below two approaches.
Approach 1:
you can find the Element using findElements
method.If the element is found, then elementList size will be 1 or more than 1 and If the element is not found, then size will be 0. So, we can return the flag based on the condition,
public boolean addNewAlertIsDisplayed(){
List<WebElement> elementList=driver.findElements(By.xpath("//*[@class='aside right am-slide-right']"));
//If the Element is not present , then the above list size will be 0, else it will have some value
if(elementList.size()>0){
return true;
}else{
return false;
}
}
Approach 2: You can check the element present using the try catch block as below
public boolean addNewAlertIsDisplayed(){
try{
driver.findElement(By.xpath("//*[@class='aside right am-slide-right']"));
return true;
}catch(NoSuchElementException e ){
return false;
}
}
Upvotes: 2