Reputation: 1334
I am constructing a div and appending it to a main div. While doing this I need to get the height of the div as soon as I construct it and before appending it.
For Example,
<script>
$(function(){
var text = $("#ObjText").html(); // This text is dynamic
var dv = $("<div id='childDiv'>"+text+"</div>");
alert($(dv).height()); // This is getting '0' - Need to get the height of the div here.
$("#page").append(dv);
//After appending to page able to get the height of the child div
alert($("#childDiv").height());
});
</script>
In my body Tag,
<body>
<div id="page"></div>
</body>
Please help me out on this. Thanks in advance.
Upvotes: 7
Views: 10329
Reputation: 3065
I don't think you can get height of any object you create in runtime before appending it to the document.
jQuery executes and gets result of all DOM ready object available on the document(your html) There fore before appending u cannot get the height.
If you still want to get the height i can suggest u a temporary place div on html where you can append your current div and check the height. if you want you and append the div where you want later.
Hope the above helps you to find the solution...
Upvotes: 7
Reputation: 87
Insert it with style="display: none"
, and then use the normal jquery .height() to obtain the height. Show it with .show() when needed.
Upvotes: -2
Reputation: 35793
A div that hasn't been added to the dom does not have a height.
What you can do is hide the div, then append it and get the height and then show the div:
$(function(){
var text = $("#ObjText").html(); // This text is dynamic
var dv = $("<div id='childDiv'>"+text+"</div>").hide(); // hide the div
$("#page").append(dv);
alert(dv.height()); // should have the correct height
dv.show();
});
Upvotes: 9