I need the full height of a div, I\'m currently using
document.getElementById(\'measureTool\').offsetHeight
offsetHeig
What about something like this (no jquery)? It's similar to @gdoron's answer but a little simpler. Tested it in IE9+, Firefox, and Chrome.
function getAbsoluteHeight(el) {
// Get the DOM Node if you pass in a string
el = (typeof el === 'string') ? document.querySelector(el) : el;
var styles = window.getComputedStyle(el);
var margin = parseFloat(styles['marginTop']) +
parseFloat(styles['marginBottom']);
return Math.ceil(el.offsetHeight + margin);
}
Here is a working jsfiddle.
var el = document.querySelector('div');
var elHeight = el.offsetHeight;
elHeight += parseInt(window.getComputedStyle(el).getPropertyValue('margin-top'));
elHeight += parseInt(window.getComputedStyle(el).getPropertyValue('margin-bottom'));
console.log(elHeight);
https://jsfiddle.net/gbd47ox1/
I think this solution is more readable, but none of the solutions presented account for sizes that aren't pixels... :(
Vanilla JavaScript ECMAScript 5.1
height
(including padding
& border
)var element = document.getElementById('myID'),
height = element.getBoundingClientRect().height,
style = window.getComputedStyle(element);
// height: element height + vertical padding & borders
// now we just need to add vertical margins
height = ["top", "bottom"]
.map(function(side) {
return parseInt(style['margin-' + side], 10)
})
.reduce(function(total, side) {
return total + side
}, height)
// result: compare with devtools computed measurements
document.querySelector('.result').innerText = 'Total height is: ' + height + 'px';
#myID {
padding: 10px 0 20px;
border-top: solid 2px red;
border-bottom: solid 3px pink;
margin: 5px 0 7px;
background-color: yellow;
}
.result {
margin-top: 50px;
}
<div id="myID">element</div>
<div class="result"></div>
Another functional solution using arrow functions:
let el = document.querySelector('div');
let style = window.getComputedStyle(el);
let height = ['height', 'padding-top', 'padding-bottom']
.map((key) => parseInt(style.getPropertyValue(key), 10))
.reduce((prev, cur) => prev + cur);