Skip to content Skip to sidebar Skip to footer

Element Offsetheight Always "0"

Why I am getting Element offsetHeight '0'? even element original height is not showing

Solution 1:

Sometimes offsetHeight will return zero because the element you've created has not been rendered in the Dom yet. I wrote this function for such circumstances:

functiongetHeight(element)
{
    element.style.visibility = "hidden";
    document.body.appendChild(element);
    var height = element.offsetHeight + 0;
    document.body.removeChild(element);
    element.style.visibility = "visible";
    return height;
}

Solution 2:

You are trying to get offsetHeight of a hidden element. the css .navbar ul li ul has display:none that would make all of it's content invisible, including crossobj and you can't get height of elements that are not displayed, their height is simply put 0.

Solution 3:

Another "trick" is to momentarily set the objects visibility to hidden, its display to block. And then get the offsetHeight. Then just reverse that by setting display to none and visibility to visible. Of course this will only work if it will not disrupt the flow of the page layout (i.e. everything shifts in the page as if something is there, but nothing is displayed in the space). But if it is something that is z-indexed or floating or perhaps absolute positioned it should work fine.

Solution 4:

UPDATE

Changes applied to the DOM elements are not applied immediately, all the changes made to the DOM in a single execution cycle are collected and applied in one repaint.

So you need to wait for the repaint to complete before trying to read the updated dimensions of the element.

requestAnimationFrame is a method that is executed before every repaint.

requestAnimationFrame(() => {
    /* should be able to get offsetHeight here */
};

Solution 5:

There is a more easiest way to do that. I had many iframes with different IDs and names so here is what I did. I added the button in the parent window, which on click does this

var iWin = document.querySelector(your iframe id here).contentWindow;
iWin.postMessage("button is clicked","*");
//you can send the id of the required frame as the message

Put this inside the child window script.

window.onload = function(){
          window.addEventListener('message',(e)=>{
            if(e.data == "showcomment"){
              //I am just sending the height and iframe name cause I have many iframes //with different names  window.parent.postMessage({winHeight:document.body.offsetHeight,winName: 
              window.name},"*");
            }
          });
    }

Now last step put this in the parent window script

window.addEventListener('message',(e)=>{
//here I am getting element with that name and setting its height you can change itdocument.getElementsByName(`${e.data.winName}`)[0].height = e.data.winHeight + 10;
//I added 10 as extra height , you can ignore it

})

Post a Comment for "Element Offsetheight Always "0""