bsullit
bsullit

Reputation: 111

how to Check invisibility of Element X, if it is invisible, click this Element Y

I want to check if "X" element is visible, if it is not visible, then click button "Y" that will display button "X"

I tried the following examples

This first example, breaks due to "driver" is unable to find this locator. What is the best approach to check if this element is Not visible and then click the other button in order to display it?

if (!(driver.findelement(XBUTTONlocator).Displayed))
{
    driver.Navigate().GoToUrl(VariablesConstants.ManageWizardURL);
    Thread.Sleep(2000);
    YBUTTONlocator.Click();
    Assert.IsTrue(driver.FindElement(By.CssSelector("")).Displayed);
}

I also have this Expected condition but I do not know of how to implement it in a IF, and then make an action.

public static Func<IWebDriver, bool> InvisibilityOfElementLocated(By locator)
{
    return (driver) =>
    {
        try
        {
            var element = driver.FindElement(locator);
            return !element.Displayed;
        }
        catch (NoSuchElementException)
        {
            return true;
        }
        catch (StaleElementReferenceException)
        {
            return true;
        }
    };

HTML of button I want to verify it's displayed:

<span translate="" class="ng-scope ng-binding">Create Distribution Group</span>

Upvotes: 0

Views: 587

Answers (2)

DMart
DMart

Reputation: 2461

Try/catch should work.

try{
    driver.findelement(XBUTTONlocator).click()
}
catch (NoSuchElementException) {
    YBUTTONlocator.click()
}

Conversely you could also use findElements and check to see if it's size is 0.

if(driver.findelements(XBUTTONlocator).size > 0) {
    driver.findelements(XBUTTONlocator).click()
} else {
    YBUTTTONlocator.click()
}

Upvotes: 0

Guy
Guy

Reputation: 50864

driver.FindElement will return the located WebElement if found or will throw NoSuchElementException if not. You can use driver.FindElements. If the returned list is empty the element doesn't exist, and if the list is not empty you can use index to check visibility of the element

ReadOnlyCollection<IWebElement> elements = driver.FindElements(XBUTTONlocator);
if (elements.Count == 0 || !elements[0].Displayed)
{
}

Upvotes: 4

Related Questions