Monday, March 7, 2011

jQuery's ready function and the "this" keyword

A few days ago, I got some hard time when my belief about the 'simple' this keyword of jQuery busted.

I had this simple html code
<div class="parent">
   <div class="child"></div>
   <div class="child"></div>
   <div class="child"></div>
</div>
I simply want to count the number of children inside the parent div. And instead of writing the counting code inside $(document).ready() as I have always been writing, I decided to narrow down the scope to the parent div only (because I had no reason to wait for the whole doc to be ready) and that was where the story begun.
$("#parent").ready() {
$(this).children().length; // return 1
$("#parent").children().length; // return 3
}
There is something wrong here, within $("#parent").ready(), $(this) and $("#parent") selectors are supposed to refer to the same object, the parent div. But the result turned out to be something different.

And thank for #stackoverflow, I got my answer. After all, the $.ready() function is ALWAYS run on the document element, no matter what selector are you using. To find an evidence for this, I tried:
$("#parent").ready() {
      $(this).children().each(function(){
              console.log($(this).html()); // the whole html
      });
        $("#parent").children().each(function(){
              console.log($(this).html()); // the children divs' content
      });
}
Apart from increasing code's clarity and understandability, you should stick with $(document).ready() because that is where everything get executed at the end of the day.