dramasea
dramasea

Reputation: 3490

Why does the javascript style property not work as expected?

<html>
   <head>
       <style type="text/css">
       #wow{
          border : 10px solid red;
          width: 20px;
          height: 20px;

       }
       </style>
   </head>
   <body>
      <div id="wow"></div>
      <script>
        var val = document.getElementById("wow");
        alert(val.style.length);
      </script>
   </body>
</html>

This is my code, why is val.style.length 0? Because I defined 3 properties, I expect it to be 3

Upvotes: 2

Views: 403

Answers (1)

lonesomeday
lonesomeday

Reputation: 237847

An element's style property only reflects inline styles. It is essentially a way of getting (and indeed setting) inline styles.

From MDN:

[the style property] is not useful for learning about the element's style in general, since it represents only the CSS declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the section, or external style sheets.

You can get all the styles applied to an element with window.getComputedStyle(element):

alert(window.getComputedStyle(val).length);

However, this probably won't do what you want, since it provides all the style properties on an element, even if they are still the default. In my browser (Chrome, FWIW), that means it always returns 285. This shouldn't be a surprise. The browser has a "built in" stylesheet that provides the defaults for all elements, after all.

Upvotes: 4

Related Questions