I’m creating some HTML elements dynamically via JavaScript. Something line this:
var author = document.createElement("div");
author.innerHTML = _feed[i].author;
author.className = "author";
The browser returns offsetHeight = 0 if the element is not added to the document yet.
I want to know the element’s height before appending them to the document because if the element’s resulting height is too big I need to take some actions (make it smaller), and only after that add it to the document.
Dan the problem you are going to have is that unless you add it to the DOM then you can never accurately know what the height will be. The reason for this is that as the element is not in the DOM, it cannot be affected by styles set in CSS or the browsers default styles. Even if the element itself has no specific styles applied to it then its parent element may do, or even its grandparent element (did I just make grandparent element up?).
The only accurate way of getting the height is to place the element exactly where it will sit in the DOM and then detect the height. I don’t think
visibility:hidden;will work as its presence will still be felt by elements around it (pushing margins around and positioning of other elements).How about
position:absolute; left: -5000px;? That may work.