Determine the height of a dynamically populated HTML table

I would like to draw a diagram in HTML. The positioning structure looks like this:

<div id='hostDiv'> <div id='backgroundDiv'> ... drawing the background ... </div> <div id='foregroundDiv' style='position: absolute;'> ... drawing the foreground ... </div> </div> 

In the foreground is a table element that is dynamically filled with text, so the row heights can vary depending on the amount of text entering the cell. How can I predict the final height of a table element in foregroun? I need this information to set the correct background height. Is there a way to pre-render a table from Javascript and read its height? Or some other trick?

PS. The size of hostDiv may change as the size of the browser changes.

+4
source share
5 answers

It is impossible to predict height without actually rendering in the target browser.

Once you do this, you can use (for example) jQuery to get the height of the element:

 var height = $('#myTable').height(); 
+5
source

When using jquery, you can find out the height of the table before rendering it to the user. Use this construct (a liberal borrowing code from a person above me):

 $(document).ready(function () { var height = $('#myTable').height(); }); 
+3
source

You cannot predict the total height of an element before loading after the browser displays and places the elements depending on the neighboring elements and the size of the viewport.

However, you can use most js libraries to find what you are looking for. In Prototype, this is:

 $('navlist-main').offsetHeight 

This will recursively add the rendering height (and not just the style height) for each child element and any associated margins and indents, and will return the exact number for the element height.

+1
source

If you just don't want to display the table before resizing the dived foregorund:
Set style.visibility = "hidden" on the table. Unlike display: none, this does not remove the div from the document stream, and so the foreground div will still be the right size (the table just won't be visible).

Of course, if this is acceptable, you can move the foregroundDiv to backgroundDiv and remove the absolute positioning. backgroundDiv will automatically resize to contain foregroundDiv (and the table).

+1
source

I think you can use one of the DOM attributes: clientHeight, offsetHeight and scrollHeight, as defined in w3 here

This is using clientHeight:

 document.getElementById("#Table").clientHeight; document.getElementById("#Table").clientWidth; 
0
source

Source: https://habr.com/ru/post/1277392/


All Articles