Selenium C# Webdriver How to detect if element is visible

user1442482 picture user1442482 · Jun 7, 2012 · Viewed 48.1k times · Source

Is there a way in the latest version of Selenium DotNet Webdriver (2.22.0) to check to see if an element is visible before clicking/interacting with it?

The only way I've found is to try to handle the ElementNotVisible exception that occurs when you try to send keys, or click on it. Unfortunately this only occurs after an attempt to interact with the element has been made. I'm using a recursive function to find elements with a certain value, and some of these elements are only visible in certain scenarios (but their html is still there no matter what, so they can be found).

It's my understanding that the RenderedWebElement class is deprecated as well other variants. So no casting to that.

Thanks.

Answer

Arran picture Arran · Jun 7, 2012

For Java there is isDisplayed() on the RemoteWebElement - as well is isEnabled()

In C#, there is a Displayed & Enabled property.

Both must be true for an element to be on the page and visible to a user.

In the case of "html is still there no matter what, so they can be found", simply check BOTH isDisplayed (Java) / Displayed (C#) AND isEnabled (Java) / Enabled (C#).

Example, in C#:

public void Test()
{
    IWebDriver driver = new FirefoxDriver();
    IWebElement element = null;
    if (TryFindElement(By.CssSelector("div.logintextbox"), out element)
    {
        bool visible = IsElementVisible(element);
        if  (visible)
        {
            // do something
        }
    }
}

public bool TryFindElement(By by, out IWebElement element)
{
    try
    {
        element = driver.FindElement(by);
    }
    catch (NoSuchElementException ex)
    {
        return false;
    }
    return true;
}

public bool IsElementVisible(IWebElement element)
{
    return element.Displayed && element.Enabled;
}