admin管理员组

文章数量:1289828

I am creating two divs:

var div_day=document.createElement("div");
var div_dateValue=document.createElement("div");

I then want to add div_day to an existing calendar div and div_dateValue to div_day:

$('#calendar').append(div_day)                          
$(div_day).append(div_dateValue);

div_day gets added to calendar, but div_dateValue does not get added to div_day, and the script stops there. No errors in the console but it is in a loop and should have more div_days (each with a unique id). I am new to jquery so any help is appreciated.

In my search I have found how to add divs, but not to add a dynamically created div to another dynamically created div.

Thanks for your help!

Kevin

I am creating two divs:

var div_day=document.createElement("div");
var div_dateValue=document.createElement("div");

I then want to add div_day to an existing calendar div and div_dateValue to div_day:

$('#calendar').append(div_day)                          
$(div_day).append(div_dateValue);

div_day gets added to calendar, but div_dateValue does not get added to div_day, and the script stops there. No errors in the console but it is in a loop and should have more div_days (each with a unique id). I am new to jquery so any help is appreciated.

In my search I have found how to add divs, but not to add a dynamically created div to another dynamically created div.

Thanks for your help!

Kevin

Share Improve this question asked Jul 25, 2011 at 16:33 Bring Coffee Bring BeerBring Coffee Bring Beer 1,1213 gold badges13 silver badges19 bronze badges 3
  • Have you tried creating your div tags using jQuery from the very beginning? var div_day = $("<div>").html("Tuesday"); I'm not entirely sure what your problem is without seeing more code, but it's a thought... – jbrookover Commented Jul 25, 2011 at 16:36
  • If you c/p'd as is, you're missing a semicolon after the first line – tkm256 Commented Jul 25, 2011 at 16:37
  • @tkm256 Semicolon would not cause this problem because of the carriage return after the line. – Joseph Marikle Commented Jul 25, 2011 at 16:39
Add a ment  | 

3 Answers 3

Reset to default 2
div_day.appendChild(div_dateValue)
$('#calendar').append(div_day)  

Something else must be going on (even with your missing semi-colon). Your example works fine here:

http://jsfiddle/P4rh5/

But, instead of creating divs with straight javascript, you can do it with jQuery:

var div_day = $("<div>");
var div_dateValue = $("<div>");

$('#calendar').append(div_day);                        
$(div_day).append(div_dateValue);

Of course, you could do this in a single step:

$('#calendar').append("<div><div></div></div>");
$('<div><div></div></div>').appendTo("#calendar");

Try this and mark it as answer if it helps

本文标签: javascriptAdding a dynamically created div to another div with jqueryStack Overflow