I have a question about scrolling to an element. I have this code below where I can filter out how to click an element based on its name:
public class LandingPage extends BasePage {
public LandingPage(WebDriver webDriver) {
super(webDriver);
}
By cardBody = By.className("card-body");
public void clickCard(String cardName) {
List<WebElement> elements = webDriver.findElements(cardBody);
click(
elements.stream()
.filter(element -> element.getText().equalsIgnoreCase(cardName))
.collect(Collectors.toList())
.get(0));
}
}
I want to do a similar thing but instead of clicking on an element, I want to scroll to the element. Does anyone know how to do this?
CodePudding user response:
For true
it scrolls element to the top and for false
it scrolls element to the bottom. In below code I am scrolling till last element of the list.
Code:
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
List<WebElement> optionList = driver.findElements(By.xpath("xPath to list of elements"));
int lastElement = (optionList.size() - 1);
javascriptExecutor.executeScript("arguments[0].scrollIntoView(false);",optionList.get(lastElement));
If you want to scroll till specific element then you can pass the element id.
javascriptExecutor.executeScript("arguments[0].scrollIntoView(false);",optionList.get(3));
CodePudding user response:
to scroll to a specific element in Java-Selenium bindings, we use JavascriptExecutor
like below.
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", ele)
here ele
is a WebElement
where you want to scrollIntoview
Since you have a list of web elements, elements
in your case, you could probably use elements.get(0)
or elements.get(1)
.
or best way would be to iterate through the list and have JavascriptExecutor
in your loop.
Something like :
for(WebElement ele : elements){
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", ele)
// do some stuff with ele.
}