Why browser is returning empty string on style.height ? How to get actual height of an element?

10,198

Solution 1

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>

Solution 2

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.

Solution 3

Use clientHeight or offsetHeight property. Check this url

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

Solution 4

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.

Share:
10,198
rsk82
Author by

rsk82

Updated on June 15, 2022

Comments

  • rsk82
    rsk82 about 2 years

    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.