title: Click button if it is present, else click a different button in puppeteer
body: <p>I am trying to set up an <code>if/else</code> statement in puppeteer to click on a button if it is present, else click on another button. I am doing something like this:</p>
  
  <pre><code>if (document.querySelector('#buttonToClick') !== null) {
      await page.waitForSelector('#buttonToClick');
      await page.click('#buttonToClick');
    } 
  
  else { 
  // first click #otherButton and then click #buttonToClick
      await page.waitForSelector('#otherButton');
      await page.click('#otherButton');
  
      await page.waitForSelector('#buttonToClick');
      await page.click('#buttonToClick');
    }
  </code></pre>
  
  <p>For some reason I keep falling into the <code>else</code> block even when I go to my Chrome console and do a <code>document.querySelector('#buttonToClick') !==null</code> on the desired page and it is showing as <code>true</code></p>
  
  <p><strong>UPDATE</strong>: The following code seems to be working for me, but I am not sure why </p>
  
  <pre><code>await page.waitFor(3000);
  
    if ((await page.$('#buttonToClick')) !== null) {
      await page.click('#buttonToClick');
    } else {
      await page.waitForSelector('#otherButton');
      await page.click('#otherButton');
  
      await page.waitForSelector('#buttonToClick');
      await page.click('#buttonToClick');
    }`
  </code></pre>
  
  <p>I thought maybe it might have something to do with the way the DOM loads, so I tried:</p>
  
  <pre><code>await page.waitForNavigation({waitUntil: 'domcontentloaded'})
  // await page.waitFor(3000)
  
    if ((await page.$('#buttonToClick')) !== null) {
      await page.click('#buttonToClick');
    } else {
      await page.waitForSelector('#otherButton');
      await page.click('#otherButton');
  
      await page.waitForSelector('#buttonToClick');
      await page.click('#buttonToClick');
    }
  </code></pre>
  
  <p>But that didn't work...it only works with <code>await page.waitFor(30000)</code> before the <code>if</code> statement...any ideas why?</p>