Created a local variable and output the resulting html entity, but returns null . What's the catch? I did the same thing outside self-calling, the same thing.

 (function(){ var elem = document.getElementById('js_elem'); // инпут на странице с таким айди console.log(elem); })(); 
  • By the way, there is not enough self-challenge in the question. - Qwertiy
  • @Qwertiy, There is no self-call, but the result ( null ) is. Magic, cho! - user207618
  • @Other, nedokipipastil ... - Qwertiy

3 answers 3

You have javascript code running before building an element with id: js_elem . Two solutions:

  1. Connect the js-file at the end (bottom) of the html-template.
  2. Wait until the document is fully loaded.

    a )

     (function(){ document.addEventListener("DOMContentLoaded", ready); function ready(){ var elem = document.getElementById('js_elem'); console.log(elem); }; )(); 

    b ) Using jQuery:

     (function(){ $(document).ready(ready); function ready() { var elem = $('#js_elem'); console.log(elem); } })(); 
  • 2
    Just wondering - why use the jQuery function to wait for a load, but not use $ to search for an item? - user207618
  • @Other you are right, add the right example to your answer. - Max
  • I didn’t have an example, yours, in general, is correct, just strange. Correct yourself if you want. - user207618
  • The self-invoking function in this variant is not very useful. - Qwertiy
  • one
    @dirk, before loading a document from a script, you can only refer to elements that are before it in the markup (hmm .. did not check that there is with document.write). To that after - it is impossible. Even document.body will be null if the script is in head. - Qwertiy

I do not see the whole page, but surely you are looking for an element before building a DOM .
There is nothing before him. Wait for the document DOMContentLoaded event and find everything.

It is also possible to add to the end of the document, but there may be strange glitches.

    Your function does not call itself. To do this, add brackets:

     <div id="js_elem"></div> <script> (function() { var elem = document.getElementById('js_elem'); console.log(elem); })(); // <--- вот тут </script> 
    • If this were the reason, the null output would not be discussed. This is probably just a mistake in the question. Also: "Did the same thing outside pickup - the same thing" - Qwertiy