title: Selenium, Java stale element reference with PageFactory
body: <p>Hi all i've recently started learning selenium and I just made my first test. Sadly this tests is very flaky and fails about 30 % of the time due to:</p>
  <blockquote>
  <p>org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document</p>
  </blockquote>
  <p>I thought using the PageFactory.initElements was a way to combat this. Yet it does not seem to work. Here is how i've implemented it.</p>
  <pre><code>public class PageObject  {
      public PageObject() {
          final WebDriver webDriver = WebDriverManager.getDriverFromPool();
          PageFactory.initElements(new AjaxElementLocatorFactory(webDriver, 10), this);
      }
  }
  
  class Frontpage extends PageObject {
      @FindBy(id=&quot;search-results&quot;)
      private WebElement results;
  
      @FindBy(id=&quot;search&quot;)
      private WebElement searchBox;
  
      public Frontpage() {
          super();
      }
  
      public void resultPrinter() {
          List&lt;WebElement&gt; resultList = results.findElements(By.tagName(&quot;tr&quot;));
          for(WebElement element : resultList) {
              System.out.println(element.getAttribute(&quot;id&quot;)); //this part is flaky
          }
      }
  
      public void searchForUser(String user) {
          searchBox.click();
          searchBox.clear();
          searchBox.sendKeys(user);
      }
  }
  </code></pre>
  <p>and here is how its used:</p>
  <pre><code>public void userSearchTest() {
      Frontpage fp = new Frontpage();
      fp.searchForUser(&quot;Adam&quot;);
  }
  
  public void validateUserResult() {
      Frontpage fp = new Frontpage();
      fp.resultPrinter(); //fails here sometimes
  }
  </code></pre>