What is the equivalent of .height() and .width() of jQuery in pure JavaScript?
According to the http://youmightnotneedjquery.com/ it's
parseFloat(getComputedStyle(el, null).height.replace("px", ""))
and
parseFloat(getComputedStyle(el, null).width.replace("px", ""))
for IE9+.
Well, I have managed to come to a solution. For browsers except IE<9, Window.getComputedStyle()
is to the rescue. The Window.getComputedStyle()
method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain. See https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle for more details on that.
Problem is with IE 8 and earlier. getComputedStyle
is undefined
in them. Fortunately IE has proprietary currentStyle
property from which we could retrieve content width
and height
. Sad but true that, if we declared width
in %
in stylesheets, it would return in %
also.
So the problem remains is, we need a way to convert from percentage to pixel values. There is a hack from Dean Edwards for solving this problem. Thanks to him !
var PIXEL = /^\d+(px)?$/i;
function getPixelValue(element, value) {
if (PIXEL.test(value)) return parseInt(value);
var style = element.style.left;
var runtimeStyle = element.runtimeStyle.left;
element.runtimeStyle.left = element.currentStyle.left;
element.style.left = value || 0;
value = element.style.pixelLeft;
element.style.left = style;
element.runtimeStyle.left = runtimeStyle;
return value;
};
So, finally the cross-browser solution of finding content width( logic for calculating height is same except query for height instead of width ) using the hack is as follows:
Suppose we have a div
with id 'container'
. Its width is set as 50% in the style sheet.
<style type="text/css">
#container {
width: 50%;
padding: 5px;
}
</style>
Test JavaScript Code:
var container = document.getElementById('container');
if (window.getComputedStyle) {
var computedStyle = getComputedStyle(container, null)
alert("width : "+computedStyle.width);
} else {
alert("width : "+getPixelValue(container,container.currentStyle.width)+'px');
}
document.getElementById("elemID").clientWidth;
document.getElementById("elemID").clientHeight;
Here elemID
is the element ID