0

Following an example: http://jsfiddle.net/UcQ39/

HTML:

<div id="test" class="test">Test</div>

CSS:

.test{height: 90px; border: 1px solid black;}

Javascript:

alert(document.getElementById('test').style.height);

I want to show the height or another property of the div but the alert is empty. How to solve? The height is in a class, i don't want to move it in a id.

user3154581
  • 61
  • 1
  • 5
  • please, post the code also in your question – Fabrizio Calderan Jan 16 '14 at 12:49
  • possible duplicate of [CSS / JavaScript - How do you get the rendered height of an element?](http://stackoverflow.com/questions/526347/css-javascript-how-do-you-get-the-rendered-height-of-an-element) – Andy Jan 16 '14 at 12:52
  • 1
    `getComputedStyle(document.getElementById('test')).height` [window.getComputedStyle](https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle) – Givi Jan 16 '14 at 12:52
  • With plain javascript: http://stackoverflow.com/questions/15615552/get-div-height-with-plain-javascript – cs_stackX Jan 16 '14 at 12:57
  • Or you can use jQuery: http://api.jquery.com/height/ – cs_stackX Jan 16 '14 at 12:57

4 Answers4

1
document.getElementById('test').style.height

Refers to the height property defined in a style attribute.

But in your code you have not a style attribute, so you can get the total height of the element with

document.getElementById('test').offsetHeight 
/* return 92 (90 + 2px borders ) */

or (if you also need to read other properties)

window.getComputedStyle(document.getElementById('test')).getPropertyValue("height")
/* return "90px" */
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
0

element.style reads element's style property.

If you had <div style="height:100px"> you could read its .style.height.

To get what's specified by CSS you should use getComputedStyle method, but for dimensions it would be best to use offsetHeight / offsetWidth.

BTW: reading from style property or using getComputedStyle gives you the value and the unit, which may be "10px" or "2%" or "7em" and is pretty much useless if you need the pixel dimensions of an element.

pawel
  • 35,827
  • 7
  • 56
  • 53
0

Use this:

document.getElementById('test').offsetHeight;
Shhade Slman
  • 263
  • 2
  • 10
0

I don't have much idea about these emulators. But when you put your javascript on page load, the javascript gets called first. And then the page elements gets set.

If you want this alert in your code, add the <script> tag after <html> tag and write your alert in that. This should work.

Keyur Golani
  • 573
  • 8
  • 26