Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Getting height of the constructed div

Tags:

html

jquery

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.

like image 902
Max Avatar asked Jan 04 '12 09:01

Max


1 Answers

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();
});

http://jsfiddle.net/MPtvK/

like image 88
Richard Dalton Avatar answered Oct 22 '22 12:10

Richard Dalton