Selenium Check if Element Exists

Profile picture for user arilio666

In selenium, we can check whether an element exists on a page using the findElement() and isDisplayed() methods. This article will discuss how we can check whether the element is visible using the above.

  • We will use the programsbuzz login page to enter incorrect credentials and then check whether the error message appears or not after the wrong inputs.
public static void main(String[] args) throws InterruptedException {
        ChromeDriver driver = new ChromeDriver();
        driver.findElement(By.xpath("//input[@value='Log in']")).click();
        boolean errorMessage = driver.findElement(By.xpath("//div[@class='messages messages--error']")).isDisplayed();
        if (errorMessage) {
            System.out.println("Incorrect Credentials");
        } else {
            System.out.println("No Error Message");
  • Here we entered an incorrect username and password for login.
  • As soon as the error message popped, we grabbed the element and assigned isDisplayed() to it.
  • Using a simple if statement, we ensured that the error message is displayed and the element thus exists and is verified.