0

I want to get the font css property from an element. I'm using:

window.getComputedStyle(element)
  .getPropertyValue('font');

It works perfectly in Chrome, but returns "" in IE, Edge, and Firefox.

Getting each font property (font-style, font-variant, font-weight, font-size, line-height, font-family) separately works, but I'm trying to avoid building the font property myself.

Here is the HTML I'm using (and the jsbin):

<div id="elm">Foo</div>

<script>
  var elm = document.getElementById('elm');

  function css(element, property) {
      return window
        .getComputedStyle(element)
        .getPropertyValue(property);
  }

  console.log(css(elm, 'font'));
  console.log(css(elm, 'font-style'));
  console.log(css(elm, 'font-weight'));
  console.log(css(elm, 'font-variant'));
  console.log(css(elm, 'font-family'));
  console.log(css(elm, 'font-size'));
</script>

Edit:
There are similar questions for background and for border. The former is solved by using css classes, and the later by copying the style from one element to another.
I'm looking for the browser to give me the shorthand property.

Community
  • 1
  • 1
pomber
  • 23,132
  • 10
  • 81
  • 94
  • Is it still a duplicate? – pomber Dec 01 '16 at 14:51
  • `getComputedStyle` is not guaranteed to return shorthand properties, and you should not depend on it, and some browsers do not do this. The question you mention related to `background` should explain this clearly. –  Dec 02 '16 at 11:21
  • @torazaburo maybe there is another way/hack to make the browser build the shorthand property for me – pomber Dec 02 '16 at 11:24
  • @torazaburo this question is about getting the shorthand property, not each separated style – pomber Dec 02 '16 at 11:31
  • The clear answer is that **that is not possible in a reliable way**. –  Dec 02 '16 at 11:36
  • Ok, I edited the title to make it clear that I need the property shorthand, an answer to the question should suggest how to do it (probably without using `getPropertyValue('font')`) – pomber Dec 02 '16 at 11:44
  • By the way, just out of curiosity, what are you planning to do with this shorthand `font` value once you get it? –  Dec 02 '16 at 12:37
  • Related: http://stackoverflow.com/questions/10675885/get-set-css-property-values-via-javascript-questions. –  Dec 02 '16 at 12:44
  • @torazaburo set canvas font https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font – pomber Dec 02 '16 at 13:10

0 Answers0