Jquery: Appending To An Element Created In Another Function
I created a div like so: $(document).ready(function() { $(document.createElement('div')).attr('id', 'container').appendTo('body'); }); and then later, dynamically I w
Solution 1:
Your add() function is being called before $(document).ready();
Change it to this and it should work:
<htmlxmlns="http://www.w3.org/1999/xhtml"><head><scripttype="text/javascript"src="http://code.jquery.com/jquery-latest.pack.js"></script><scripttype="text/javascript">
$(document).ready(function() {
$(document.createElement("div")).attr("id", "container").appendTo("body");
add();
});
functionadd() {
var newElement = $(document.createElement("div")).attr("id", "inner");
$(newElement).appendTo("#container");
}
</script><styletype="text/css">#inner{
background-color: black;
height: 200px;
width:100px;
}
</style></head><body></body></html>
Which could be condensed to:
<htmlxmlns="http://www.w3.org/1999/xhtml"><head><scripttype="text/javascript"src="http://code.jquery.com/jquery-latest.pack.js"></script><scripttype="text/javascript">
$(function() {
$("<div/>", { id : "container" }).appendTo("body");
$("<div/>", { id : "inner"}).appendTo("#container");
});
</script><styletype="text/css">#inner{
background-color: black;
height: 200px;
width:100px;
}
</style></head><body></body></html>
Post a Comment for "Jquery: Appending To An Element Created In Another Function"