There are different ways to handle:
- Here it is checking through findElements, if no element is found then list size will be zero, if element found then the size will be greater than zero.
List<WebElement> elements = driver.findElements(By.xpath(xpathLocation));
if (elements.size() > 0) {
LOGGER.info("{} is present on the DOM.", id);
return true;
} else {
LOGGER.info("{} is not present on the DOM.", id);
return false;
}
- Here if the element is found then it'll return flag as true, if not and in case NoSuchElementException as well, it is handled and you'll get false.
/**
* Method to check if element is present.
*
* @param element
* @return
*/
public static boolean isElementPresent(WebElement element) {
try {
if (element.isDisplayed() || element.isEnabled())
return true;
} catch (Exception e) {
return false;
}
return false;
}