How to scroll a specific DIV using Selenium WebDriver with Java?

We can scroll a specific DIV using Selenium webdriver. Selenium cannot handle scrolling directly. It takes the help of the Javascript Executor to do scrolling action to a specific DIV.

First of all we have to identify the specific DIV up to which we have to scroll to with the help of xpath or css locator. Next we shall take the help of the Javascript Executor to run the Javascript commands. The method executeScript is used to execute Javascript commands in Selenium. We have to use the scrollIntoView method in Javascript and pass true as an argument to the method.


WebElement m=driver.findElement(By.xpath("//div[@class='slick-track']"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", m);


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollToDiv{
   public static void main(String[] args) {
      System.setProperty("", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // identify element
      WebElement m=driver.findElement(By.xpath("//div[@class='slick-track']"));
      // Javascript executor
      ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", m);


Updated on: 26-Oct-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started