Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jun 2006
    Location
    UK
    Posts
    892
    Thanks
    301
    Thanked 2 Times in 2 Posts

    Question Question about accessing DOM via jQuery

    Hi

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

    http://jsbin.com/izuzud/1/edit

    But the following works?

    http://jsbin.com/efujar/1/edit

    The code is exactly the same same except the position.

  • #2
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,479
    Thanks
    6
    Thanked 981 Times in 954 Posts
    This is because you are executing the script before the element is even existing. If you include the script in the head you need to wait for the DOM to be loaded. Have you confused the self-invoking function with the jQuery DOM ready function or why are you using it?

    PHP Code:
    $(function(){
      $(
    '#mybutton').click(function(){
        var 
    = $('#mydiv').text();
        
    alert(a);
      });
    }); 
    The self-invoking function isn’t even necessary, if you put the script at the end of the document you can even do
    PHP Code:
    <script type="text/javascript">
    $(
    '#mybutton').click(function(){
      var 
    = $('#mydiv').text();
      
    alert(a);
    });
    </script> 

  • #3
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    Both code samples contain the following construct
    Code:
    (function() {
       ...
    })(jQuery);
    which doesn't make any sense in that case. It creates an anonymous function with no parameter which will be immediately called with the parameter jQuery. The parameter will not be matched to anything so it will be lost.

    The position of the code matters in that case because the function will be executed immediately and the element '#mybutton' will only exist before the end of the <body>

    This is probably what you wanted to do instead
    Code:
    $(function() {
       ...
    });


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •