2

Possible Duplicate:
Get a CSS value with JavaScript

could you tell me why I cant get these css properties when I load the page?

code at jsFiddle

javascript:

function aviso(){
    alert("top: "+document.getElementById("divRojo").style.top);
    alert("position: "+document.getElementById("divRojo").style.position);
}

HTML:

<html>
    <head>
        <style type="text/css">
            #divRojo {
                width:100px;
                height:100px;
                background:red;
                left:200px;
                top:200px;
                position:static;
        }
    </style>
</head>

<body onload="aviso()">
    <div id="divRojo">
        Div Rojo
    </div>
</body>

</html>

Thanks in advance

Community
  • 1
  • 1
aprendiz
  • 21
  • 1

1 Answers1

2

It's because the DOMElement.style property contains inline styles -- it does not contain style rules applied via CSS.

Use getComputedStyle to get the applied styles:

var el = document.getElementById("divRojo");
alert(window.getComputedStyle(el).top);
alert(window.getComputedStyle(el).position);

JSFiddle

McGarnagle
  • 101,349
  • 31
  • 229
  • 260