title: selenium find element in a while loop in java
body: <p>So, I have a selenium webdriver command that is a condition for the while loop as shown here: </p>
  
  <pre><code>            while (driver.findElement(By.cssSelector("a[action='cancel']")).isDisplayed() == true){
              driver.navigate().refresh();
  
              TimeUnit.SECONDS.sleep(5);
              driver.findElement(By.id("479510558845313")).sendKeys(InstagramAievx.spamusernameinput);
  
              driver.findElement(By.id("263795143794707")).sendKeys(InstagramAievx.spamcommentinput);
  
              driver.findElement(By.id("u_0_4")).sendKeys(x);
              driver.findElement(By.id("u_0_5")).click();
          }
  
          TimeUnit.SECONDS.sleep(2);
          driver.findElement(By.xpath("//a[contains(text(),'Okay')]")).click();
          killFirefox();
  </code></pre>
  
  <p>So, my problem is that when the condition is false, it does not skip the while loop and go to what's below it. It tries to do this : <code>driver.findElement(By.cssSelector("a[action='cancel']"))</code> which makes the program fail. How do I make it skip it when it's false ands go to what's out of the loop? Thanks.</p>