Reputation: 25
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.
Upvotes: 1
Views: 2115
Reputation: 3721
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
Upvotes: 0
Reputation: 10830
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.
Upvotes: 3
Reputation: 8706
Everything is OK in your code. See here
And see another approach of creation elements here.
Upvotes: 2