JSFiddle - React, Tailwind, and code Playground
by gleezer
HTML
<button id="starter"> Calculate heights </button>
<!-- hiddenParent is between two other divs but takes no space in the document as it's display:none -->
<div id="hiddenParent" style="display: none;">
<div class="childDiv">child div 1</div>
<div class="childDiv">child div 2</div>
<div class="childDiv">child div 3</div>
</div>
<div class="another-div">
here's another div
</div>
CSS
#hiddenParent, .another-div{
background: teal;
width: 40%;
padding: 20px;
text-align: center;
color: white;
font-family: Arial;
text-transform: uppercase;
color: #ccc;
}
.childDiv{
background: purple;
padding: 10px;
margin-bottom: 10px;
}
.another-div{
background: orange;
color: #1F9091;
}
JavaScript
var par = document.getElementById('hiddenParent'),
cd = par.querySelectorAll('.childDiv'),
len,
heights = [],
i;
function getHeight(){
len = cd.length;
// 1.we hide the parent
par.style.visibility = 'hidden';
// 2. we set its position to absolute, so it does not
// take space inside the window
par.style.position = 'absolute';
// 3. we set its display to block so it will gain back its natural height
par.style.display = 'block';
// 4. we start looping over its children
while(len--){
// we get the height of each children... here we're just storing them in array,
// which we will alert later
heights[len] = window.getComputedStyle( cd[len] ).getPropertyValue('height');
}
// 5. Job is done, we can bring back everything to normal (if needed)
par.cssText = 'display: none';
}
document.getElementById('starter').addEventListener('click',function(){
getHeight();
alert(heights);
});