Search code examples
seleniumselenium-webdriverdrag-and-dropwebdriverdraggable

NoSuchElementException: no such element: Unable to locate element:while identifying draggable and droppable element


I am actually new to selenium. I am trying to do drag and drop operation on a demo website : http://jqueryui.com/droppable/ (Here go to demo-->Droppable).

Following is my html source :

<div id="draggable" class="ui-widget-content ui-draggable ui-draggable-handle" style="position: relative;">
    <p>Drag me to my target</p>
</div>

Following is my code block :

WebElement drag=dr.findElement(By.xpath("//*[@id='draggable']"));
wait.until(ExpectedConditions.elementToBeClickable(drag));

WebElement drop=dr.findElement(By.xpath("//*[@id='droppable']"));

wait.until(ExpectedConditions.elementToBeClickable(drop));
//act.moveToElement(drop).build().perform();
act.dragAndDrop(drag, drop).build().perform();

Solution

  • The element to drag and the element to drop are within an <iframe>. So you have to switch to the intended frame first then locate the draggable and droppable elements and perform dragAndDrop() as follows :

    Here is the complete code snippet :

    System.setProperty("webdriver.gecko.driver", "C:\\path\\to\\geckodriver.exe");
    WebDriver driver=new FirefoxDriver();
    driver.get("http://jqueryui.com/droppable/");
    driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
    driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@class='demo-frame']")));
    WebElement  from = driver.findElement(By.id("draggable"));
    WebElement  to = driver.findElement(By.id("droppable"));
    new Actions(driver).dragAndDrop(from, to).build().perform();
    System.out.println("Drag and Drop Completed");
    driver.quit();