13

Simple one line of html:

<div onclick="alert(this.style.height)">sometext</div>

and alert gives:

but it should be like 10px or sth like that.

Community
  • 1
  • 1
rsk82
  • 28,217
  • 50
  • 150
  • 240
  • Did you try setting the style explicitly? `
    sometext
    `
    – Martin Hennings Jan 10 '11 at 11:19
  • use jquery! you'll have a much more simpler time, it has the $.height() function to tell the height. Also you might find that there is no height so you have to check lineHeight and padding (top and bottom). – Jason Jan 10 '11 at 11:23
  • opera version 11, but this is irrelevant, even browser is irrelevant, I first thought that this is only opera quirk. I will change the question a little. – rsk82 Jan 10 '11 at 11:27

4 Answers4

24

When you use this.style.height, the height must have been specified on the element first, like this:

<div style="height: 15px;" onclick="alert(this.style.height)">sometext</div>

Otherwise, you should probably use offsetHeight or clientHeight:

<div onclick="alert(this.offsetHeight)">sometext</div>
DanneManne
  • 21,107
  • 5
  • 57
  • 58
  • 1
    +1 it works. But how? what is the difference between `height` and `offsetHeight`? – Kevin Jun 19 '13 at 03:57
  • 2
    The `height` is only available if you have explicitly set the height. But `offsetHeight` will always be the calculated height. If you are unsure on when to use either then one simple tip is to use `offsetHeight` when you are checking what height it has and `height` when you are setting a new height. – DanneManne Jun 19 '13 at 09:08
  • wat about `clientHeight`? is that the same as `offsetHeight`? – Kevin Jun 19 '13 at 09:17
  • See question http://stackoverflow.com/questions/4106538/difference-between-offsetheight-and-clientheight – DanneManne Jun 19 '13 at 11:32
5

My guess is that you don't actually have any style rules setting the element's height. To get the actual rendered height of an element, use element.clientHeight.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
2

object.style.whatever only returns values that have been set using the style attribute in markup, or the style property in script, thus:

<div style="height:10px" onclick="alert(this.style.height)">sometext</div>

or

theDiv.style.height = "10px";

The method getComputedStyle allows you to access the style properties, as they are defined by the cascade (i.e. using @style as above, or <stylesheet>...</stylesheet> or whatever mechanism)

EDIT: It may benefit you to use an established cross-browser JS library, rather than access this property directly, and have to deal with the quirks of diverse browsers. Older versions of IE (for example) do not support this method.

Paul Butcher
  • 6,902
  • 28
  • 39
1

Use clientHeight or offsetHeight property. Check this url

http://help.dottoro.com/ljuxqbfx.php

Shahid
  • 668
  • 8
  • 16