Lexus de Vinco
Lexus de Vinco

Reputation: 447

Why won't javascript return the style properties?

<html>
<head>
    <title>Return Width</title>
    <style type="text/css">
        #foo { background: green; width: 80px; }
    </style>
    <script type="text/javascript">
        function getWidth() {
            alert(document.getElementById("foo").style.width);
        }
    </script>
</head>
<body>
<div id="foo" onClick="getWidth()">
    Hello World
</div>

I have been trying to return several properties including width and backgroundColor and what I'm finding is that I can set the properties but I can't return them. Why?

Upvotes: 0

Views: 157

Answers (3)

depending on the property you need to access, you have other methods, like offsetwidth and offsetheight. getComputedStyles doesn`t work on ie7 and ie8, though you could try this, is cross browser

function getStyle(el, cssprop){
 if (el.currentStyle) //IE
  return el.currentStyle[cssprop]
 else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox
  return document.defaultView.getComputedStyle(el, "")[cssprop]
 else //try and get inline style
  return el.style[cssprop]
}

Upvotes: 1

j08691
j08691

Reputation: 208032

That only works for inline styles. USe getComputedStyle for CSS set via non-inline styles.

function getWidth() {
    var elem = document.getElementById("foo");
    var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("width");
    alert(theCSSprop);
}

jsFiddle example

Upvotes: 3

Quentin
Quentin

Reputation: 944555

The style property references the styles applied directly to the element (via the style property or the style attribute). It doesn't reference styles applied through the cascade.

For that, you want getComputedStyle.

Upvotes: 2

Related Questions