3

I was testing to write something in innerHTML, without any event handler. I'm wondering why Jquery document ready didn't work - I thought it was supposed to be a self invoking function? The regular self invoking function did work.

If I have this in HTML

<div id="content">
  <p><span id="html_span1"></span></p>
  <p><span id="html_span2"></span></p>
</div>    

In JS, the regular self invoking function works:

(function(){
     document.getElementById('html_span1').innerHTML = "self invoking function works";
}());    

But not Jquery ready function:

$(document).ready(function() {
    document.getElementById('html_span2').innerHTML = "Is this displayed?";
});    

If I place the Jquery function at the top, then the other function stops working - how come? Also, the self evoking function, which ends with }()); - the extra parenthesis is very important, otherwise it's not working. I don't understand the meaning of that parenthesis though?

Galivan
  • 4,842
  • 9
  • 44
  • 76

1 Answers1

1

If you are using Jquery better use selectors:

$( document ).ready(function() {
// Handler for .ready() called.
    $("#html_span2").html("Is this displayed?");
});

See it running and play with it: http://jsfiddle.net/c66t0tb2/

Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
  • 1
    Thanks, so it's not good to use regular javascript (like getElementById) in a Jquery function? Seems that I have missed some general rule.. – Galivan Nov 13 '14 at 00:24
  • No, but JQuery has a lot of powerful that you are missing. Is a JS framework to resolve a lot of problems and things. Selectors are one of the better things that JQuery has. If you already load it, why don't use it? – Leandro Bardelli Nov 13 '14 at 00:26
  • Actually JQuery is regular javascript. Is not a language. – Leandro Bardelli Nov 13 '14 at 00:28
  • Yeah, true, but then there has to be some explanation for why document.getElementById().innerHTML didn't work inside a Jquery ready function. But I'm gonna follow your advice anyhow! – Galivan Nov 13 '14 at 00:34
  • But are not the same: http://stackoverflow.com/questions/4069982/document-getelementbyid-vs-jquery – Leandro Bardelli Nov 13 '14 at 00:46
  • 1
    I did a silly mistake - something else probably caused the error originally, but when I did testings in the online editor (Codepen), I didn't realize that Jquery was (probably) not enabled there.Thanks for showing that it works. – Galivan Nov 13 '14 at 04:23
  • You're welcome. If the answer was good for you, please upvoted it. If it answers your question, please mark it as accepted. You will gain points in this way and everyone will know that you mark your answer. So the next time people will answer you more often and better. – Leandro Bardelli Nov 13 '14 at 15:05
  • 1
    Sure, but I'll have to wait until I get 15 reputation points, I will upvote once I get there. – Galivan Nov 13 '14 at 20:02
  • oh! mmmm if you ask something more comment here :) – Leandro Bardelli Nov 13 '14 at 20:11