Suppose that I have a &l
Take a look at Element.getBoundingClientRect().
This method will return an object containing the width, height, and some other useful values:
{
width: 960,
height: 71,
top: 603,
bottom: 674,
left: 360,
right: 1320
}
For Example:
var element = document.getElementById('foo');
var positionInfo = element.getBoundingClientRect();
var height = positionInfo.height;
var width = positionInfo.width;
I believe this does not have the issues that .offsetWidth and .offsetHeight do where they sometimes return 0 (as discussed in the comments here)
Another difference is getBoundingClientRect() may return fractional pixels, where .offsetWidth and .offsetHeight will round to the nearest integer.
IE8 Note: getBoundingClientRect does not return height and width on IE8 and below.*
If you must support IE8, use .offsetWidth and .offsetHeight:
var height = element.offsetHeight;
var width = element.offsetWidth;
Its worth noting that the Object returned by this method is not really a normal object. Its properties are not enumerable (so, for example, Object.keys doesn't work out-of-the-box.)
More info on this here: How best to convert a ClientRect / DomRect into a plain Object
Reference:
.offsetHeight: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight.offsetWidth: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth.getBoundingClientRect(): https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect