title: How to resolve Stale element while looping through all the buttons?
body: <p>As a part of a larger test, I have to click a particular button with no assigned ID. After browsing and trying various other solutions on stackoverflow, I thought to simply loop through all the buttons - and later think about how to select it individually and click it. Here's the code:</p>
  
  <pre><code>    List&lt;WebElement&gt; buttons = driver.findElements(By.cssSelector(".btn.btn-primary"));
      for (WebElement b:buttons) {
          System.out.println(b.getTagName());
          System.out.println(b.getText());
      }
  </code></pre>
  
  <p>The button is dynamically generated using Jquery. The actual webpage is only a collection of .js references. Here's the code I got from Inspect Element:</p>
  
  <pre><code>&lt;div class="modal-footer"&gt;
      &lt;button class="btn btn-primary" type="button" data-bb-handler="yes"&gt;Task Status&lt;/button&gt;
      &lt;button class="btn btn-primary" type="button" data-bb-handler="danger"&gt;Close&lt;/button&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>There are over 20 buttons (hardly 4-5 visible at this stage) in the process on this web page. Currently, there's a popup (background is faded) with two buttons as shown in the code section above.</p>
  
  <p>In selenium, it is throwing <strong><code>StaleElementReferenceException: stale element reference: element is not attached to the page document</code></strong> on the line that says <code>b.getTagName()</code>.</p>
  
  <p>Unsure about what might be causing this. Already tried:
  1. Implicitly waiting for 30 seconds.
  2. <code>XPath</code> selectors
  3. Polling multiple times in a loop and try-catch blocks 
  ... as mentioned in other answers. Getting same exception for all the possible solutions. </p>
  
  <p>What might be causing this?</p>
  
  <p>p.s. Can't share screenshot as this is a propriety enterprise application.</p>