How to check if an page object web element exists

How to check if an Element exists, when using Page Objects with webdriver.

Page Object:
@FindBy(how=How.XPATH, using=”//input[@name=’username’]”) WebElement userName;

I am trying to create a reusable method to check if an web element exists in page object. None of them are working

public static boolean isElementPresent(WebElement element) {
try {
return element!=0;
} catch (NoSuchElementException e) {
return false;
}

Here we cant use  FindElements() method when looking for non-present elements.
Any workaround or solution ?

Add Comment
  • 1 Answer(s)

    This is a very good question. In page objects you get proxy elements created during PageObject initialization. The only way to determine that this element is actually present or not is by making a call to do some task.

    For eg do a webelement.getText() and catch exceptions. If you get NoSuchElementException that means element is not present.

    your code will look like this

    public static boolean isElementPresent(WebElement element) {
    try {
       element.getText();
       return true;
    } catch (NoSuchElementException e) {
    return false;
    }

    Professor Answered on June 7, 2016.
    Add Comment
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.