Is there any way to get an element's height prior to appending it to the DOM? I know that clientHeight doesn't work as I've tried and it always returns 0. Are there other methods that may return the height or does the element have to be a part of the DOM in order for the height to be calculated?
This is a sample of what I'm going for:
function test(a) { var a=document.createElement(a) a.style.top=(window.innerHeight/2-a.clientHeight/2)+'px' //fixed position in CSS document.body.appendChild(a) }
*Note: This is only a simplified version of the function I'm working on in order to project what I'm trying to achieve without all of the unneeded mess.
Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.
height() It returns the current height of the element. It does not include the padding, border or margin. It always returns a unit-less pixel value. Note: The height() will always return the content height, regardless of the value of CSS box-sizing property.
The clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin. The clientHeight property is read-only.
Elements don't have a height, in any real sense, until they've been added to the DOM, as their styles cannot be evaluated until then.
You can get around this easily enough using visibility: hidden
so that the element can be added to the DOM (and its height determined) without causing visible flickering.
function test(a) { var a = document.createElement(a); a.style.visibility = 'hidden'; document.body.appendChild(a); a.appendChild(document.createTextNode('Hello')); a.style.fontStyle = 'italic'; a.style.top=(window.innerHeight/2 - a.clientHeight/2) + 'px'; a.style.visibility = ''; return a; } test('p').style.background = '#0f0';
p { position: absolute; top: 0; left: 0; }
(This is working on the assumption that you're using top
because the element is absolutely positioned or fixed. If it weren't, you'd need to make it so temporarily.) Hidden elements still take up space in the DOM (so their sizes must be calculated), but cannot actually be seen by the user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With