title: How to add event listener to body element via JavaScript?
body: <p>How can I add an <code>onload</code> event listener to the <code>&lt;body&gt;</code> element (or some other suitable near-top-level element) in an HTML document via JavaScript?</p>
  
  <p>I want to achieve the same behavior as this:</p>
  
  <pre><code>&lt;body onresize="handleResize();"&gt;
     ...
  &lt;/body&gt;
  </code></pre>
  
  <p>(i.e., when the page resizes, the function should run)</p>
  
  <p>But I want to add the event listener with JavaScript like this</p>
  
  <pre><code>(function() {
    //effectively private because it's in the closure
    function handleResize() {
      //do stuff here
    }
    element.addEventListener("resize",handleResize);
  })(); //IIFE
  </code></pre>
  
  <p>The problem I'm having is that I don't know how to grab the appropriate element to attach the event to.</p>
  
  <p>I tried this:</p>
  
  <pre><code>document.documentElement.addEventListener("resize",handleResize);
  </code></pre>
  
  <p>And this:</p>
  
  <pre><code>document.body.addEventListener("resize",handleResize);
  </code></pre>
  
  <p>But in both cases, the <code>handleResize</code> function never gets called.</p>
  
  <p>How can I access the appropriate top-level or near-top-level element?</p>