2

object.style.fontSize returning empty if set via css. But works if set using the style attribute directly on the object within html.

Is there some trick to making this work when it is set via CSS?

For instance:

<!DOCTYPE html>
<html lang="en-us">
 <head>
  <style>
   #Set_With_CSS_Style_Sheet
   {
    font-size:14pt;
   }
  </style>
 </head>

 <body onload=loaded()>

<!-- Both of these correctly sets the font size -->
<!-- JavaScript retrieves the font size when set in this manner (via style attribute). -->
  <div id="Set_With_Style_Attribute" style="font-size:10pt">CSS Font Size Test:10pt</div>

<!-- JavaScript returns empty when set in this manner (via css style sheet). -->
  <div id="Set_With_CSS_Style_Sheet">CSS Font Size Test: 14pt</div>

  <script type="text/javascript">
function loaded() {
 alert("Set With Style Attribute: " + this.document.getElementById("Set_With_Style_Attribute").style.fontSize);
 alert("Set With Style Sheet: "     + this.document.getElementById("Set_With_CSS_Style_Sheet").style.fontSize);
}
  </script>

 </body>
</html>
Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
NOYB
  • 625
  • 8
  • 14

1 Answers1

3

When the font size is set by a style sheet the fontSize property will return "", instead you should use window.getComputedStyle.

window.getComputedStyle(document.getElementById('ID'), null).getPropertyValue('font-size');
Ryan Rossiter
  • 408
  • 2
  • 11
  • 1
    Thanks Ryan. However this seems to be browser specific and returns bogus value for IE 11 (18.66px). Also, just to clarify for anyone else that finds this and tries to use it there is a typo; s/getcomputedStyle/getComputedStyle/ – NOYB Jul 22 '15 at 23:59