Bob Jones
Bob Jones

Reputation: 171

How to drag and drop in selenium when there are multiple elements

The following code is not working. The reportDataFields displays a list of items(for ex abc, abd, abe) and I want to select abc and drop into the target. It does not fisplay any error message either.

Actions action = new Actions(driver);
List<WebElement> reportFields = driver.findElements(By.className("reportDataFields"));
WebElement target = driver.findElement(By.id("rptDataSections"));

for (int i = 0; i < reportFields.size(); i++) {

    if (reportFields.get(i).getText().equals(Section)) {
        action.dragAndDrop(reportFields.get(i), target).release().build().perform();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Upvotes: 0

Views: 1337

Answers (1)

Fenio
Fenio

Reputation: 3635

I think you should create a new instance of Actions interface every time you use it.

Try below code with my personalized drag and drop functionality:

List<WebElement> reportFields = driver.findElements(By.className("reportDataFields"));
WebElement target = driver.findElement(By.id("rptDataSections"));

for (int i = 0; i < reportFields.size(); i++) {  
    if (reportFields.get(i).getText().equals(Section)) {
       WebElement draggedFrom = reportFields.get(i);
       new Actions(driver)
                .moveToElement(draggedFrom)
                .pause(Duration.ofSeconds(1))
                .clickAndHold(draggedFrom)
                .pause(Duration.ofSeconds(1))
                .moveByOffset(1, 0)
                .moveToElement(target)
                .moveByOffset(1, 0)
                .pause(Duration.ofSeconds(1))
                .release().perform();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Upvotes: 1

Related Questions