Rahul
Rahul

Reputation: 759

Selenium / Java: Alternative methods to 'isDisplayed()' for verifying if an element is present or not

It seems that .isDisplayed() method is not working in our framework.

It works fine if the element is displayed in the application. If not, it is throwing Null Pointer Exception. So, just wanted to know if there is any other method to verify if the element is present and write if-else condition accordingly.

Upvotes: 1

Views: 3916

Answers (6)

Kushal Bhalaik
Kushal Bhalaik

Reputation: 3384

You can try following method to check if the element exists:

  public boolean isPresent(By locator_of_your_element){

  List <WebElement> yourElement = driver.findElements(your locator here);

  if (yourElement.size()!=0){

      return true;
    }
    else{

     return false;
  }
  }

Upvotes: 0

Gaurang Shah
Gaurang Shah

Reputation: 12930

The reason you are getting null pointer exception is, isDisplayed() method assumes that element is already present and then checks if it's visible or not.

This is what I do to check if element is present or not?

public boolean isElementExist(By element, int timeout){
    wait = new WebDriverWait(driver, timeout);
    try{
        return wait.until(ExpectedConditions.presenceOfElementLocated(element));

    }catch (TimeoutException te){
        return null;
    }
}

you can call this method to get element Object and then check if it's displayed or not. or better you can wait until element is visible using following code.

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(a))); 

Upvotes: -1

You can enclose your code in Try and catch block and maintain condition if element display then perform your actions. If element not display then it will through the exception which will be handled by catch block.

 try
{
      if(usersname.isDisplayed())
    {
        System.out.println("Already Login");

    }
}
catch(Exception e)
{            
        new UserLogin(driver).doLogin(TestDataComman.username, TestDataComman.password);
}

Upvotes: 1

Rajnish Kumar
Rajnish Kumar

Reputation: 2938

HI you can create your own custom method to verify if a element is present on the page or not

    public boolean IsElementPresent(String locatorKey) {
    List<WebElement> e = null;
    e = driver.findElements(By.id(locatorKey));

    if (e.size() == 0) {
        return false;
    } else {
        return true;
    }
}

Hope this helps

Upvotes: 0

optimistic_creeper
optimistic_creeper

Reputation: 2799

One way other than using isDisplayd() method is:

Count the number of elements and check whether it is greater than zero

Code snippet:

boolean isPresent = driver.findElements(By.cssSelector("your selector")).size() > 0;

Upvotes: 0

RNS
RNS

Reputation: 625

You can check if element is present or not by following code :

driver.findElements( By.id("...") ).size() != 0

Upvotes: 0

Related Questions