5

Please offer insight into this mystery.

I am trying to get the height value from a div box by

var high = document.getElementById("hintdiv").style.height; 
alert(high);

I can get this value just fine if the attribute is contained within the div tag, but it returns a blank value if the attribute is defined in the css section.

This is fine, it shows 100px as a value. The value can be accessed.

<div id="hintdiv" style="height:100px; display: none;">
.
.
var high = document.getElementById("hintdiv").style.height; 
    alert(high); 

This is not fine, it shows an empty alert screen. The value is practically 0.

#hintdiv
{
height:100px
display: none; 
}

<div id="hintdiv">
.
.
var high = document.getElementById("hintdiv").style.height; 
    alert(high); 

But I have no problem accessing/changing the "display:none" attribute whether it is in the tag or in the css section. The div box displays correctly by both attribute definition methods (inside the tag or in the css section).

I also tried to access the value by other variations, but no luck

document.getElementById("hintdiv").style.height.value  ----> undefined
document.getElementById("hintdiv").height ---->undefined
document.getElementById("hintdiv").height.value  ----> error, no execution

Any solution?

TIA.

Jamex
  • 732
  • 3
  • 9
  • 17
  • 4
    See http://stackoverflow.com/questions/1098349/reading-non-inline-css-style-info-from-javascript and http://stackoverflow.com/questions/1048336/cant-access-css-selectors-properties-from-javascript – Crescent Fresh Jun 16 '10 at 01:51
  • See also: http://gist.github.com/369133 and http://stackoverflow.com/questions/2531737/javascript-incapable-of-getting-elements-max-height-via-element-style-maxheight/ – Christian C. Salvadó Jun 16 '10 at 02:14
  • Thanks all, this was certainly unexpected. I guess I will do inline style for this 1(or 2 elements). – Jamex Jun 16 '10 at 02:26

3 Answers3

5

This is because, when you use document.getElementById("hintdiv").style.height; you are accessing the style attribute of the tag. If the attribute is not there , then you get no values.

Instead you should use currentStyle object in IE and getComputedStyle() function in the rest of web browsers.

tereško
  • 58,060
  • 25
  • 98
  • 150
1

You CSS syntax is wrong, it sould be height:100px; rather than height:100px. Note the semicolon.

Pierre
  • 18,643
  • 4
  • 41
  • 62
-1

You should consider usign jQuery instead... it will simplify the thing as $('#hintDiv').height() and it will always return the actual width of the div.

Developer IT
  • 1,203
  • 2
  • 11
  • 17
  • Thanks DevIT, I need to pick up a jquery book. – Jamex Jun 16 '10 at 02:24
  • Hi epascarello ! Glad I could help... but to leanr jQuery, you dont absolutly need a book, just try the tutorials on jQuery's website: http://docs.jquery.com/Tutorials – Developer IT Jun 17 '10 at 18:34