Getting the height of an element before added to the DOM
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.
Here is a working demo of how to measure an element by briefly adding it to the DOM and inspecting its height, then removing it. This method might be costly since the node is cloned, so the added styles won't affect it afterwards and all DOM events will be removed from it.
If the inspected node has a lot of sub-nodes, this might not be efficient, but stil can be quite handy.
function getNodeHeight(node) {
var height, clone = node.cloneNode(true)
// hide the meassured (cloned) element
clone.style.cssText = "position:fixed; top:-9999px; opacity:0;"
// add the clone to the DOM
document.body.appendChild(clone)
// meassure it
height = clone.clientHeight
// cleaup
clone.parentNode.removeChild(clone)
return height
}
var newDiv = document.createElement("div");
newDiv.innerHTML = `Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
<h1>deserunt mollit anim id est laborum.<h1>`
// print the height of "newDiv"
console.log( getNodeHeight(newDiv) )