I'm trying to understand the following code:
WebElement elem = driver.findElement(By.id("123"));
JavascriptExecutor js = (JavascriptExecutor) driver
js.executeScript("arguments[0].scrollIntoView(true);",elem);
I read that this code is useful in places like Facebook where there is a paging process.
But I'm thinking that if the element will be seen only after paging, doesn't it mean that the first line WebElement Elem = driver.findElement(By.id("123"));
will throw an exception, since the element isn't part of the Dom yet (Until the paging will arrive at this item)?
CodePudding user response:
Line by line explantion:
WebElement elem = driver.findElement(By.id("123"));
the driver is a web driver reference, using that you can call findElement
method and pass the locator like id
with the help of By which is an abstract
class in selenium.
Selenium talk and communicate with HTMLDOM, so if you see 123
as an id
in HTMLDOM then there will not be any error/exception.
But if the 123
id web element is not present or not rendered properly then you would see an exception related to WebElement.
JavascriptExecutor
is basically an interface in Selenium-Java
bindings.
and this line
js.executeScript("arguments[0].scrollIntoView(true);", elem);
this line is basically taking two args. second arg
is a web element (elem
) in your case. and arguments[0]
represent the specified web element and we are invoking JS - scrollIntoView(true);
method on top of that.
CodePudding user response:
Selenium imitates a real user actions via the UI.
So, as a user you can not click etc. element that is not appearing on the visible screen view. This is why Selenium driver will throw you an exception in case you try to access such element.
However this element can exist on the DOM.
It can be completely rendered or not, depends on the specific technology how that specific web page is implemented, but the web element will exist.
JavaScript can access invisible and still not fully rendered elements. So, with JS you can perform several actions Selenium driver will not allow you to do.
But this will not imitate real human user actions via the UI.