0
<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?

Lexus de Vinco
  • 447
  • 2
  • 7
  • 20
  • You *can* access the properties that way, but `#foo` *has no* `style` attribute? – Bergi Feb 16 '13 at 14:48
  • Is there a way I can reference the styles applied through the cascade? – Lexus de Vinco Feb 16 '13 at 14:51
  • Then see [How do i get a computed style?](http://stackoverflow.com/questions/5910004/how-do-i-get-a-computed-style) – Bergi Feb 16 '13 at 14:52
  • @Bergi Is there a way I can reference the width in the css file? Or should I just set the width attribute in the html tag? – Lexus de Vinco Feb 16 '13 at 14:56
  • Setting the `style` attribute (via `el.style.width = …;`) is the simplest and best for single elements. However, it is [possible](http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript) to reference and change the applied stylesheets. – Bergi Feb 16 '13 at 15:00

3 Answers3

3

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

j08691
  • 204,283
  • 31
  • 260
  • 272
2

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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]
}