0

The following code works perfectly when an element is present in DOM and visible in the viewport:

WebElement button = webdriver.findElement(By.id("myButton"));

But, I don't understand why it throws an exception when the button is present in the DOM but not visible in the viewport.

I know for sure that the button is present: there is no ajax in play here.

How can I test for an element to be present in the DOM whether or not it is visible in the viewport?

I already saw some usefull links here on stackoverflow:

https://stackoverflow.com/a/44916498/420593

How to check if an element is into view using Selenium WebDriver?

fluminis
  • 3,575
  • 4
  • 34
  • 47

2 Answers2

0

You can use WebDriverWait along with action class to move to element and perform click onto it.

WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement button = wait.until(
        ExpectedConditions.elementToBeClickable(By.id("myButton")));
Actions actions = new Actions(driver);
actions.moveToElement(button).click().build().perform();
SeleniumUser
  • 4,065
  • 2
  • 7
  • 30
0

After some more research, that's my conclusion:

webdriver.executeScript("arguments[0].scrollIntoView()", button);
button.click();

Should work, but in my case, due to some bootstrap fixed header, the button is in the view but hidden by the fixed header over it (z-index). And an exception is thrown when the second line is executed.

Same occurred with the following:

Actions actions = new Actions(driver);
actions.moveToElement(button).click().build().perform();

So, I finally resolved my problem by simulating a click in javascript:

webdriver.executeScript("arguments[0].scrollIntoView()", button);
fluminis
  • 3,575
  • 4
  • 34
  • 47