Calculate div height given a known width?

To accurately determine the height of the div and the image. This is because the image will likely finish loading last - if the height of the container is checked before the image is loaded, it will return height without taking the image height into consideration.

A listener should be added to the image so it checks the height once the image loads.

img.addEventListener('load', onLoad);

Because the styling is simple, offsetHeight and clientHeight should work but to include the entire element (with border and margin) use scrollHeight as described by Element.scrollHeight on MDN web docs

The resulting code:

<div id="Content">
    <img id="Image" src="https://picsum.photos/id/82/200/150" />
    ...
</div>
<br/>
<span id="Result"></span>
<script>
    var img = document.getElementById("Image");

    function onLoad() {
        var div = document.getElementById("Content");
        var res = document.getElementById("Result");

        res.innerHTML = div.scrollHeight;
    }

    img.addEventListener('load', onLoad);
</script>

The whole example is in a CodeSnadbox here:

Edit calculate div height - known width - JS


I am not sure I completely understand your question, but you can use javascript to calculate the height of a div.

var height = document.getElementsByTagName('div').offsetHeight;

You have to use window.onload instead.

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading. ref

In your case you need to wait for the image and not only the DOM.

window.onload = function() {
  var div = document.getElementById("Content");
  var res = document.getElementById("Result");

  res.innerHTML = div.offsetHeight; 
};
div {
  width: 400px;
}

img {
  float: left;
  margin: 0.5em;
}
<div id="Content">

  <img src="https://picsum.photos/id/82/200/150" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Orci phasellus egestas tellus rutrum. Tempor nec feugiat nisl pretium fusce.
  Cras pulvinar mattis nunc sed blandit libero volutpat sed cras. Purus sit amet luctus venenatis lectus magna fringilla urna. Ut tristique et egestas quis. Mauris cursus mattis molestie a iaculis at erat pellentesque adipiscing. Iaculis eu non diam phasellus
  vestibulum lorem sed risus ultricies. Semper quis lectus nulla at. Augue interdum velit euismod in. Amet aliquam id diam maecenas ultricies mi eget. Scelerisque viverra mauris in aliquam sem fringilla ut morbi. Et egestas quis ipsum suspendisse. Et
  malesuada fames ac turpis. Fermentum iaculis eu non diam phasellus vestibulum lorem sed.

</div>
<br/>
<span id="Result"></span>

Tags:

Javascript

Css