1

i've started learning about javascript closures, and while experimenting, i realised that the following code does not work as expected:

(function($){
    var p='<p style="color:red">12345</p>';
    $p=$(p);
    $("body").append($p);
    $p.appendTo($("body"));
    console.log($p);
})(jQuery)

in the console, i can see the jquery object being returned, but its not being appended to the body (i have tried both the append and appendto methods).

can someone please explain to me why this code does not work as expected?

i had a thought: this may have been because jquery is not loaded by the time this function is called, however, the jquery object IS being output to the console, so that must mean jquery IS loaded at the time that this function is called.

can any knowledgeable person shed some light?

3
  • 1
    Works for me? - jsfiddle.net/yUJ48 Commented Nov 28, 2011 at 22:53
  • The jsfiddle works because it inserts the script into an onLoad block, so the body element is available. If you change the fiddle to "no wrap (head)" you can reproduce the issue (jsfiddle.net/yUJ48/1). The script is running immediately, before the page has been declared. David has the answer. Commented Nov 28, 2011 at 23:01
  • $p=$(p); ?? Why? Also why always using $p? Commented Nov 28, 2011 at 23:03

1 Answer 1

3

Make sure the body is available when the script is executed, you can do that using the shorthand domready callback:

jQuery(function($){
    var p = '<p style="color:red">12345</p>';
    $p = $(p).appendTo(document.body);
    console.log($p);
});
Sign up to request clarification or add additional context in comments.

3 Comments

I really don't see the need for $p all the time. jQuery(function($){ var p = $('<p style="color:red">12345</p>'); p.appendTo($("body")); }); Would have worked just fine as well
@omarello or just $('<p style="color:red">12345</p>').appendTo(document.body); but the question was not about optimizing the code....
i feel very stupid right now. ofcourse! the body is not ready! thanks David! @omarello, the $p was residue from some other testing, and i just wanted to understand the core issue, and not optimize it, as David has correctly pointed out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.