About the problem of inserting a piece of html code into an empty div and then getting the height of the div

now there is an empty div on the page. I insert a html into it with js, and then get the height of the div. I find that sometimes the height of the div is not accurate. What can you do to solve it?

Apr.02,2022

paste the code out, otherwise you don't know what happens


add a line document.body.scrollHeight; to force emptying the layout queue


before getting it.
insert a html into it with js, and then get the height of the div

Note that to get the height after the DOM rendering is complete, you can use

.addEventListener('DOMContentLoaded',function(){    // .attachEvent (IE 678)

or

setTimeout(() => { .. }, 0)

because it takes time to insert dom and render it, sometimes the rendering is not finished when you get the height (especially after you have just executed the insert dom logic followed by the method to get the height). So it will cause the problem of obtaining the height incorrectly!

you can add a timer:

setTimeout(() => {
  // ...
}, 20);

The

dom operation results in Reflow, which is not a problem if you insert block-level elements (web rendering process: html- > css- > js). However, if you insert inline elements (especially images) and the previous html- > css operation does not give height, then height can only be reflected in the rendering process, and you do not finish rendering when you get the height, so it will cause height problems. The solution has been given by the great gods to obtain height through setTimeout delay. All the answers without code are hooligans, and the pictures are added by themselves.

<div class="bgImg"></div>

<script>
    var odiv = document.getElementById('bgImg');
    odiv.innerHTML = '<img src="test.jpg">'
    
    setTimeout(() => {
        var oHeight = odiv.scrollHeight;
        console.log(oHeight);
    },100)
</script>
Menu