I have "div" element with specified width and height expressed in percents in CSS.
I would like to get by JS script its width and height expressed in pixels. It's even possible?
You can use
el.clientHeight;
el.clientWidth;
(el
is a reference to the element)
Demo
Note those properties were first introduced in the MS IE DHTML object model. More recently they were standardized in CSSOM View Module, W3C Working Draft 22 February 2008.
Those properties were widely supported. However, it's possible than an old non-MS compliant browser doesn't support them. In those cases, you can use getComputedStyle
:
function findSize(el, size) {
/* size must be 'width' or ' height' */
return window.getComputedStyle
? getComputedStyle(el,null).getPropertyValue(size)
: el['client'+size.substr(0,1).toUpperCase() + size.substr(1)] + 'px';
}
findSize(el, 'width');
findSize(el, 'height');
Demo
Browser support of getComputedStyle
and clientHeight
/clientWidth
way is at least:
| IE | Firefox | Chrome | Safari | Opera
-----------------|-----------------------------------------
getComputedStyle | 9 | <=3 | 1 | <=4 | <=10
client | <=5 | <=3 | 1 | <=4 | <=10
(<=n
means that it's supported at least from version n
, but I couldn't test previous versions)
Use window.getComputedStyle()
for this
<div style="wdith:50%">50% width</div>
(function() {
var div = document.getElementsByTagName("div")[0];
console.log(window.getComputedStyle(div, null)["width"]);
}())
fiddle
Supported by all major browsers and IE9+. For lower versions of IE have a look at currentStyle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With