Kai
Kai

Reputation: 2073

element.style display incorrect information

There is a simple html and javascript code:

<html>
    <head>
        <style>p { height: 100px;} </style>
        <script>
            window.onload = function(){
                var p = document.getElementsByTagName("p")[0];
                alert("actual height is " + p.style.height);
            };
        </script>
        <title>JavaScript Tests</title>
    </head>
    <body>
        <p>
            100px height p element
        </p>
    </body>
</html>

But when we run it actual height is equal to empty string.
Could you please explain why?
Thanks.

Upvotes: 3

Views: 456

Answers (2)

Ming-Tang
Ming-Tang

Reputation: 17651

The style property is different from the actual style in CSS: It looks for the style attribute, so this:

<p style="height: 100px"></p>
<script>alert(document.getElementsByTagName("p")[0].style.height);</script>

will be "100px".

To get its actual height, use getComputedStyle().

<style> p { height: 100px; }</style>
<p></p>
<script>alert(getComputedStyle(document.getElementsByTagName("p")[0]).getPropertyValue("height"));</script>

Upvotes: 2

cdhowie
cdhowie

Reputation: 169018

The style property refers to style attributes set explicitly on the element, not styles inherited from CSS declarations.

For example, try this:

<p style="height: 100px;">

Then you will see a value. See this document for an approach that will combine all of the various pieces of style information together to retrieve the actual composite style of an element.

Upvotes: 2

Related Questions