How can I javascript get element width and height of a
From my experience, a straightforward approach here is to use offsetWidth
and offsetHeight
. These properties give the layout width and height of an element, taking padding and borders into account (but not margins). This method is reliable and has great support across all browsers, so you won’t have to worry about compatibility issues.
var div = document.getElementById('myDiv');
var width = div.offsetWidth;
var height = div.offsetHeight;
With offsetWidth
and offsetHeight
, you can quickly grab the element’s width and height without diving into too much CSS or styling.
In my experience, if you need more precision, especially for elements with transformations or dynamic styling, getBoundingClientRect()
is a fantastic option. This method not only returns the element’s size but also its position relative to the viewport, making it handy if you want to center the element with more accurate positioning. getBoundingClientRect()
is well-supported in all modern browsers, so it’s another solid choice.
var div = document.getElementById('myDiv');
var rect = div.getBoundingClientRect();
var width = rect.width;
var height = rect.height;
getBoundingClientRect()
gives you the exact position and size, which is useful when working with more complex layouts.
Another technique that’s often useful is window.getComputedStyle()
, which gives you the computed CSS properties of an element. This is especially helpful if the width and height are defined in the stylesheet rather than directly on the element. With getComputedStyle
, you can accurately access the dimensions of the element after all CSS rules have been applied.
var div = document.getElementById('myDiv');
var computedStyle = window.getComputedStyle(div);
var width = parseFloat(computedStyle.width);
var height = parseFloat(computedStyle.height);
Using window.getComputedStyle()
allows you to handle situations where CSS rules might alter the width and height of an element in ways that aren’t immediately visible in the DOM properties.