0

I'm a noob with jQuery and was wondering why this needed the "jQuery(function() {});" for my .each() to work.

Given a simple table with 5 rows ( tags), I wanted to loop through all the tags and just print out the index. So in this example, I would expect to see 1,2,3,4,5 in my console log. It seems like it has something to do with the .each() method?

One thing to note is that I'm able to add a clicking event $(#someId).live('click', function()... That seems to work fine outside of the jQuery(function(){}); block...so I'm a little confused as to why the .each() didn't work.

Thanks.

<script type="text/javascript">

    jQuery(function() {
        $("#table_id > tr").each(function(index) {
            console.log(index);
        });
    });

</script>
Cavachon
  • 2,819
  • 4
  • 21
  • 20
  • The `jQuery(function(){})` block waits until the DOM is loaded before executing any code. In other words, if you didn't wait, you would be trying to access `#table_id` before it existed. This guarantees that it's loaded first. – KyleMit Jun 11 '13 at 16:33
  • ah..that makes sense. So the code was executing BEFORE the table elements were loaded with out the jQuery(function(){}) block. – Cavachon Jun 11 '13 at 16:57

2 Answers2

1

Wrapping your code in jQuery(function() { ... }); or $(document).ready(function(){ ... }); both accomplish the same thing: waiting for your page to finish loading before executing any JavaScript/jQuery code.

Mooseman
  • 18,763
  • 14
  • 70
  • 93
  • Just one note: Be aware that when .ready() triggers, it doesn't mean that everythings as been loaded (like images), use $(window).load(function({}); for that. – Maresh Jun 11 '13 at 16:34
1
jQuery(function() { ... });

is shorthand for

jQuery(document).ready(function () { ... });

and what it does is queue up a function to run when the document "is ready" to be interacted with.

Failure to wait for the document to be ready could mean that you try to access elements that don't yet exist in the DOM, so using this construct avoids this.

Take a look at http://learn.jquery.com/using-jquery-core/document-ready/ for more details.

Russ Cam
  • 124,184
  • 33
  • 204
  • 266