1

Can someone kindly enlighten me why the following code of mine does not work?

   for(var i=0; i<4; i++) {

        var ref = i+1;

        $("#test").append("<div id='t" + ref + "'>In t" + ref + "</div>");
    }

My intention is to create child divs inside 'test' div. But when I check with '$("#test > div").size()', it returns '0'. I've also tried some other alternative including the one mentioned in 'Dynamically Generating Divs with jQuery based on variable number' post, but this also return the same result '0'.

I am using "jquery-1.6.4.js" (also tried with "jquery-1.6.2.js").

Hope someone can point out what am I doing wrong.

5
  • 2
    Does this code reside in a ready handler? Commented Nov 1, 2011 at 6:04
  • If you still stuck, supply live link. Commented Nov 1, 2011 at 6:14
  • @Frederic: no it doesn't reside in ready handler. Commented Nov 1, 2011 at 6:17
  • @nyeinzay, that would be the problem, then. See Greg Pettit's answer. Commented Nov 1, 2011 at 6:25
  • @ Frédéric: Thx. That's indeed is the problem. Now solved after wrapping up with a 'ready' handler. Commented Nov 1, 2011 at 7:25

3 Answers 3

3

Everything is fine. You are probably trying to execute that code before jQuery is loaded or the DOM is ready, but then you are testing with the .size() function once everything is in place.

Make sure you wrap it all up in the document ready function and you should be good.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Greg Pettit. Now I know that the problem is with me, not with the code :). I just pick-up javascript and jQuery 2 days ago (for my school project) and still need to learn a lot.
2

Everything is OK in your code. See here

And see another approach of creation elements here.

1 Comment

Thanks, InviS. It seems I've got to read a few more things about javascript and jQurey to apply it correctly.
0

For a better practice put $ function for the HTML code

 $("#test").append( $ ("<div id='t" + ref + "'>In t" + ref + "</div>") );

And try

$("#test > div").length

or

$("#test>div").length

3 Comments

Since you don't actually NEED the $ for this to work, I'm curious (in a "I want to learn" way, not a sarcastic way) about why this is a better practice. I get that it's making a node before appending, but doesn't jQuery just do that implicitly if you don't do it explicitly?
I don't actually know it too. I got it from K++ multiple gold dudes from SO. :)
Thanks, Moe Sweet, for the suggestion.

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.