JQuery - Getting the height of a constructed div

I create a div and add it to the main div. When doing this, I need to get the height of the div as soon as I build it, and before adding 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 tag tag

 <body> <div id="page"></div> </body> 

Please help me with this. Thanks in advance.

+7
source share
3 answers

I do not think that you can get the height of any object created at runtime before adding it to the document.

jQuery executes and gets the result of the entire ready-made DOM object available in the document (your html). Therefore, before adding u cannot get height.

If you still want to get the height, I can offer you a temporary div place in html where you can add the current div and check the height. if you want you to add a div where you want later.

We hope this helps you find a solution ...

+6
source

And a div that has not been added to dom has no height.

What you can do is hide the div, then add 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/

+8
source

Paste it with style="display: none" and then use plain jquery.height () to get the height. Show it with .show () when necessary.

-2
source

All Articles