Off-DOM element dimension

It can be really frustrating; you want to know the height of an element, but it is not in the DOM yet. Since the element’s width and height depends on the styling, the measures can only be calculated on screen, in the DOM.

Size & Styling

Your best shot is adding the element to the body in a hidden state (visibility: hidden) or off-screen (position: absolute; left: -9999px;), get the width and height and remove it from the DOM. But sometimes the size of the element depends on the css of an ancestor element, like width: 100%;, which is not present in the body. Or better, you can also append the element to the eventual element, but only if that one exists and sometimes it doesn’t.

Family-tree-substitute

If it doesn’t, we could replicate it. We can make a structure that will ‘mimic’ the eventual structure that the elements dimension depends on. An example:

The size of the paragraph depends on the ancestor elements; when it is a child of a section with the class .column it will have a maximum width of 300px and, since it has a larger font-size than the default 12px, will be higher than outside of the column.

Now, lets replicate the ancestors. I use the jQuery css-parser I wrote to create the elements.

This function will replicate the family tree needed to get the proper dimensions and can be used as simple as this:

Ok, this only works if you now the chain of ancestors, but hey, even the web can’t be perfect…

Leave a Reply

Your email address will not be published. Required fields are marked *