Alpha
Alpha

Reputation: 14076

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

I have to check if an element is in view and if not, only then scroll it into view using following and then interact with it -

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);

If an element is in view, don't execute above command. To check if an element is in view, isDisplayed() is not helping because it returns true irrespective of an element is in view or not.

Can you please suggest what will help to achieve to check if an element is in view?

Upvotes: 3

Views: 3380

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193308

To interact with an element the element needs to be within the Viewport. If the element is not within the Viewport you have to scroll() as follows:

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);

You can find a detailed discussion on different scrolling option in What is the difference between the different scroll options?


At this point it is worth to mention, the following methods:

will automatically scroll the element within the Viewport before getting executed.

You can find a detailed discussion in Selenium python Error: element could not be scrolled into view


Finally, in the rarest of the rare cases if the HTML DOM comprises of Angular or React elements you may even have to induce WebDriverWait for the visibilityOfElementLocated() before you attempt to scroll as follows:

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("button.nsg-button"))));

Upvotes: 1

Related Questions