Java – Selenium 2.0 WebDriver: Element is no longer attached to the DOM error using Java

automationdomjavaselenium-webdriverwebdriver

I'm using the PageObject/PageFactory design pattern for my UI automation. Using Selenium 2.0 WebDriver, JAVA, I randomly get the error: org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM, when I attempt logic like this:

@FindBy(how = HOW.ID, using = "item")
private List<WebElement> items

private void getItemThroughName(String name) {
    wait(items);

    for(int i = 0; i < items.size(); i++) {
        try {
            Thread.sleep(0500);
        } catch (InterruptedException e) { }

        this.wait(items);
        if(items.get(i).getText().contains(name)) {
            System.out.println("Found");
            break;
        }
    }
}

The error randomly happens at the if statement line, as you can see I've tried a couple things to avoid this, like sleeping a small amount of time, or waiting for the element again, neither works 100% of the time

Best Answer

First if you really have multiple elements on the by with the ID of "item" you should log a bug or talk to the developers on the site to fix that. An ID is meant to be unique.

As comments on the question already implied you should use an ExplicitWait in this case:

private void getItemThroughName(String name) {
    new WebDriverWait(driver, 30)
               .until(ExpectedConditions.presenceOfElementLocated(
                 By.xpath("id('item')[.='" + name + "']")
               ));
    // A timeout exception will be thrown otherwise
    System.out.println("Found");
}