javascript: getElementById is not finding element
<p>Explain to my why this works when I click the button.</p>

<pre><code>&lt;script type="text/javascript"&gt;
  function myFunction() {
    if (screen.width &lt;= 800) {
      document.getElementById('cover-img').style.display = 'none';
    }
  }
&lt;/script&gt;
&lt;input type="submit" onclick="myFunction()"&gt;
</code></pre>

<p>While this does not:</p>

<pre><code>&lt;script type="text/javascript"&gt;
  if (screen.width &lt;= 800) {
    document.getElementById('cover-img').style.display = 'none';
  }
&lt;/script&gt;
</code></pre>

<p>It returns the error: </p>

<blockquote>
  <p>Uncaught TypeError: Cannot read property 'style' of null</p>
</blockquote>