title: jQuery unable to find element unless inside doc ready
body: <p>I started with this simple code with the aim of calculating the selector once.</p>
  
  <pre><code>(function($) {
  
      var $mydiv = $('.mydiv');
      var myFunc = function(){
           $mydiv.css('background', 'red');
      }
  
      $(document).ready(function(){
          myFunc();
      });
  
      $(document).resize(function(){
          myFunc();
      });
  
  })(jQuery);
  </code></pre>
  
  <p>But I'm only able to get it to work by moving the selector inside of the doc ready but I dont understand why I need to do this.</p>
  
  <pre><code>(function($) {
  
      var $mydiv;
      var myFunc = function(){
           if(!$mydiv){
               $mydiv = $('.mydiv');
           }
           $mydiv.css('background', 'red');
      }
  
      $(document).ready(function(){
          myFunc();
      });
  
      $(document).resize(function(){
          myFunc();
      });
  
  })(jQuery);
  </code></pre>