title: JavasScript wait for web element to be visible and click it
body: <p>I'm trying to automate some tasks with JavaScript. Website is being generated so I cannot use CSS selectors as they change with every website refresh. It is not shown in the example but it is possible to manipulate buttons with their text content (which CSS, sadly, cannot get). </p>
  
  <p>I have figured out (thanks to StackOverflow) how to click web element by its Xpath but still don't know how to tell JS to wait until it is present.</p>
  
  <p>Code for clicking element (working):</p>
  
  <pre><code>var xPathRes = document.evaluate ('//*[@id="tsf"]/div[2]/div/div[3]/center/input[1]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  xPathRes.singleNodeValue.click();
  </code></pre>
  
  <p>Attempt to wait for element to be present and then click it (not working):</p>
  
  <pre><code>var selector = "//*[@id='tsf']/div[2]/div/div[3]/center/input[1]";
  var time = 500;
      if(document.evaluate (selector, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)) {
          selector.singleNodeValue.click();
          return;
          }
      else {
          setTimeout(function() {
          waitForElementToDisplay(selector, time);
          }, time);    
      }
  </code></pre>
  
  <p>As you can see code in the example is Google.com search button. </p>
  
  <p>I have always used Python Selenium to do such things but in this case I really cannot. </p>
  
  <p>PS. I suck at JS as it is evident from posted code. </p>
  
  <p>Thank you for trying to help!</p>
  
  <p>EDIT:</p>
  
  <p>Following @folo code I wrote something like this:</p>
  
  <pre><code>var element = '//*[@id="tsf"]/div[2]/div/div[3]/center/input[1]';
  (function checkIfElemExists() {
     if (!document.evaluate (element, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)) {
       console.log('nope')
       window.requestAnimationFrame(checkIfElemExists);
     } else {
       console.log('okay i exist now! lets do something.') 
     }
   })()
  </code></pre>
  
  <p>The problem is that it always returns "Okay i exist now!). Even when i run it on a website that does not contain this element. </p>