isElementPresent in selenium 2.0

I really like Rostislav Matl's alternative Moving to Selenium 2 on WebDriver, Part No.1:

driver.findElements(By.className("someclass")).size() > 0;

Javadoc: org.openqa.selenium.WebDriver.findElements(org.openqa.selenium.By by)


In the Selenium 2 world, if you want to find if an element is present you would just wrap the find call in a try catch because if it isnt present it will throw an error.

try{
  driver.findElement(By.xpath("//div"));
}catch(ElementNotFound e){
  //its not been found
}

You can implement it yourself using pure webdriver:

private boolean isElementPresent(By by) {
    try {
        driver.findElement(by);
        return true;
    } catch (NoSuchElementException e) {
        return false;
    }
}

Not a part of Selenium 2, you can do the following:

// Use Selenium implementation or webdriver implementation 
Boolean useSel = false;

/**
     * Function to enable us to find out if an element exists or not.
     *
     * @param String An xpath locator
     * @return boolean True if element is found, otherwise false.
     * @throws Exception
     */
    public boolean isElementPresent(String xpathLocator) {
        return isElementPresent(xpathLocator, false, "");
    }

/**
     * Function to enable us to find out if an element exists or not and display a custom message if not found.
     *
     * @param String An xpath locator
     * @param Boolean Display a custom message
     * @param String The custom message you want to display if the locator is not found
     * @return boolean True if element is found, otherwise false.
     * @throws Exception
     */
    public boolean isElementPresent(String xpathLocator, Boolean displayCustomMessage, String customMessage) {
        try {
            if (useSel) {
                return sel.isElementPresent(xpathLocator);
            } else {
                driver.findElement(By.xpath(xpathLocator));
            }
        } catch (org.openqa.selenium.NoSuchElementException Ex) {
            if (displayCustomMessage) {
                if (!customMessage.equals("")) {
                    System.out.print(customMessage);
                }
            } else {
                System.out.println("Unable to locate Element: " + xpathLocator);
            }
            return false;
        }
        return true;
    }