Question about accessing DOM via jQuery

Hi

Can someone please tell me why does the following code snippet does NOT work

But the following works?

The code is exactly the same same except the position.

Browsers execute code immediately as it becomes available. That means that in your first snippet, you’re trying to select the button before the browser has reached the button markup.

In that case, should not the onclick button event should trigger the “Hello World” text after the browser has rendered all the DOM elements?

In the first snippet, the click event is never attached, because there’s no button yet to attach it to.

Isn’t this how you attach a click event?

$(‘#mybutton’).click(function(){
//my code here
});

Yes, but only if the element you’re selecting exists in the DOM. In your first snippet, you’re trying to select the button before the browser has reached the markup, so the button isn’t in the DOM yet.

ok but how come the same snippet works if i wrap it inside a $(document).ready() event?

Because that delays your code from executing until the DOM has been fully loaded.

I see but I thought the following two are the same:

$(document).ready(function(){

});

AND

(function(){

})(jQuery);

Probably the second form you’re thinking of is:

jQuery(function ($) {

});

ok but the question is, are the following both the same?

$(document).ready(function(){

});

and

jQuery(function ($) {

});

Yes.