Drake
Drake

Reputation: 3891

Javascript style issue

I am using javascript to display the height of my current div.

This is an example of the effected area

//css
.test
{
height:1px;
}

#test1
{
margin:1px;
}

//html
<div id="test1" class="test"></div>

//javascript
var a = document.getElementById('test1');

a.style.height //how I access the style

Firebug says that the length of style is 0 and height is empty. How can I access the correct height?

Upvotes: 1

Views: 90

Answers (4)

Praveen Lobo
Praveen Lobo

Reputation: 7187

Try a.offsetHeight instead of a.style.height

jsfiddle demo

Upvotes: 2

Tyler Egeto
Tyler Egeto

Reputation: 5495

Check out the getComputedStyle method. It should do what you are looking for. Kinda lame, really, I wish this was handled better in the DOM.

Upvotes: 0

Mike Samuel
Mike Samuel

Reputation: 120516

You need to look at the computed style, not the specified style. See Quirks mode's getstyle page which answers the question

Sometimes you'll want to see what styles the default document view has. For instance, you gave a paragraph an width of 50%, but how do you see how many pixels that is in your users' browser?

and it explains how to derive and use the getstyle function, though it's easier to use a library like jquery which provides a simple css function.

Upvotes: 3

Mrchief
Mrchief

Reputation: 76218

div height is dependent on its children. If its empty, it'll be 0.

The code you have to get height is correct, btw.

Upvotes: 0

Related Questions