Selenium: check if element exists

30-10-2019 door Roy de Kleijn

Sometimes it can be very useful to check if an element exists on a page. The code below demonstrates how to do that.

public void checkIfElementExists() {

if (driver.findElements("elementNotExists")).size() != 0) {
System.out.println("Element exist");
} else {
System.out.println("Element doesn't exist");

It returns a list of WebElements matching the locator and then it evaluates if the size is not equal to 0

Please be aware:
1. If you use an implicitlyWait it can that longer if the element doesn't exists.
2. The use of implicitlyWait is not the best. I highly recommend WebDriverWait.